-
Notifications
You must be signed in to change notification settings - Fork 87
/
BestTimeToBuySellStocks-2
41 lines (37 loc) · 1.31 KB
/
BestTimeToBuySellStocks-2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Constraints:
1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
*/
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
boolean purchased = false;
int pp = -1;
for (int i=0; i<prices.length-1; i++){
int priceDiff = prices[i+1] - prices[i];
if(priceDiff < 0){
//tomorrow lower price. buy tomorrow
//if available, sell today
if(purchased){
maxProfit += (prices[i]-pp);
purchased=false;
}
}
else if (priceDiff > 0) {
//tomorrow higher price. sell tomorrow, if available
// buy today
if (!purchased){
purchased=true;
pp = prices[i];
}
}
}
if (purchased)
maxProfit += (prices[prices.length-1] - pp);
return maxProfit;
}
}