@@ -14,41 +14,31 @@ If you were only permitted to complete at most one transaction (ie, buy one and
14
14
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
15
15
16
16
17
- Example 2:
17
+ Example 2:
18
18
Input: [7, 6, 4, 3, 1]
19
19
Output: 0
20
20
21
21
In this case, no transaction is done, i.e. max profit = 0.*/
22
22
23
23
public class _121 {
24
+
24
25
/**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 ;
27
32
int minBuy = prices [0 ];
28
33
int maxSell = prices [1 ];
29
34
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 ++) {
31
36
minBuy = Math .min (minBuy , prices [i ]);
32
37
maxProfit = Math .max (maxProfit , prices [i ] - minBuy );
33
38
}
34
39
return maxProfit ;
35
40
}
36
41
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
-
52
42
public static void main (String ...strings ){
53
43
// int[] prices = new int[]{7,1,5,3,6,4};
54
44
// int[] prices = new int[]{7,6,4,3,1};
0 commit comments