Skip to content

Commit aa6a4f6

Browse files
edit 121
1 parent 86ad427 commit aa6a4f6

File tree

1 file changed

+9
-19
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+9
-19
lines changed

src/main/java/com/fishercoder/solutions/_121.java

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,41 +14,31 @@ If you were only permitted to complete at most one transaction (ie, buy one and
1414
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
1515
1616
17-
Example 2:
17+
Example 2:
1818
Input: [7, 6, 4, 3, 1]
1919
Output: 0
2020
2121
In this case, no transaction is done, i.e. max profit = 0.*/
2222

2323
public class _121 {
24+
2425
/**Pretty straightforward, sell before you buy, keep a global maxProfit variable, update it along the way if necessary.*/
25-
public int maxProfit_20160924(int[] prices) {
26-
if(prices == null || prices.length < 2) return 0;
26+
27+
/**The key here is that you'll have to buy first, before you can sell.
28+
* That means, if the lower price comes after a higher price, their combination won't work! Since you cannot sell first
29+
* before you buy it.*/
30+
public int maxProfit(int[] prices) {
31+
if (prices == null || prices.length < 2) return 0;
2732
int minBuy = prices[0];
2833
int maxSell = prices[1];
2934
int maxProfit = (maxSell - minBuy) > 0 ? (maxSell - minBuy) : 0;
30-
for(int i = 1; i < prices.length; i++){
35+
for (int i = 1; i < prices.length; i++) {
3136
minBuy = Math.min(minBuy, prices[i]);
3237
maxProfit = Math.max(maxProfit, prices[i] - minBuy);
3338
}
3439
return maxProfit;
3540
}
3641

37-
/**The key here is that you'll have to buy first, before you can sell.
38-
* That means, if the lower price comes after a higher price, their combination won't work! Since you cannot sell first
39-
* before you buy it.*/
40-
public int maxProfit(int[] prices) {
41-
//use current price to deduct the previous min to get current profit, and then take the max from previousMax and this newly calculated max
42-
if(prices == null || prices.length < 2) return 0;
43-
int min = prices[0], prevProf = 0, currPro = 0;
44-
for(int i = 1; i < prices.length; i++){
45-
currPro = Math.max(prices[i] - min, prevProf);
46-
min = Math.min(min, prices[i]);
47-
prevProf = currPro;
48-
}
49-
return currPro;
50-
}
51-
5242
public static void main(String...strings){
5343
// int[] prices = new int[]{7,1,5,3,6,4};
5444
// int[] prices = new int[]{7,6,4,3,1};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy