Skip to content

Commit f0e41cb

Browse files
EASY/src/easy/BestTimeToBuyAndSellStock.java
1 parent 71a28e6 commit f0e41cb

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

EASY/src/easy/BestTimeToBuyAndSellStock.java

+9-12
Original file line numberDiff line numberDiff line change
@@ -43,19 +43,16 @@ public static void main(String...strings){
4343
System.out.println(test.maxProfit(prices));
4444
}
4545

46-
public int maxProfit_attemp1(int[] prices) {
47-
if(prices == null || prices.length < 2) return 0;
48-
int minBuy = prices[0], maxSell = prices[1], maxProfit = 0;
46+
47+
/**Pretty straightforward, sell before you buy, keep a global maxProfit variable, update it along the way if necessary.*/
48+
public int maxProfit_20160924(int[] prices) {
49+
if(prices == null || prices.length == 0 || prices.length < 2) return 0;
50+
int minBuy = prices[0];
51+
int maxSell = prices[1];
52+
int maxProfit = (maxSell - minBuy) > 0 ? (maxSell - minBuy) : 0;
4953
for(int i = 1; i < prices.length; i++){
50-
if(maxSell > minBuy){
51-
maxProfit = Math.max(maxProfit, maxSell-minBuy);
52-
}
53-
if(prices[i] < minBuy){
54-
minBuy = prices[i];
55-
}
56-
if(prices[i] > maxSell){
57-
maxSell = prices[i];
58-
}
54+
minBuy = Math.min(minBuy, prices[i]);
55+
maxProfit = Math.max(maxProfit, prices[i] - minBuy);
5956
}
6057
return maxProfit;
6158
}

0 commit comments

Comments
 (0)