@@ -14,41 +14,31 @@ If you were only permitted to complete at most one transaction (ie, buy one and
1414max. 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:
1818Input: [7, 6, 4, 3, 1]
1919Output: 0
2020
2121In this case, no transaction is done, i.e. max profit = 0.*/
2222
2323public 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