122. Best Time to Buy and Sell Stock II
Last updated
Last updated
public int maxProfit(int[] prices) {
int maxProfit= 0, buyPrice = -1;
for (int i = 0; i < prices.length -1; i++ ) {
if(prices[i] <= prices[i+1]) {
// hold if bought earlier
// if we haven't baought earlier buy now
if(buyPrice == -1) buyPrice = prices[i];
} else {
if(buyPrice != -1) {
maxProfit += prices[i] - buyPrice;
// to check if we can buy on same day for profit
buyPrice = -1;
i--;
}
}
}
// we bought at some point but couldn't sell
// as everyday price increased so sell on the last day
if(buyPrice != -1) {
maxProfit += prices[prices.length-1] - buyPrice;
}
return maxProfit;
}