Skip to content

Instantly share code, notes, and snippets.

@adeekshith
Created September 29, 2022 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeekshith/8703b6dd1dd02dbb639a9c3ce209e96c to your computer and use it in GitHub Desktop.
Save adeekshith/8703b6dd1dd02dbb639a9c3ce209e96c to your computer and use it in GitHub Desktop.
121. Best time to buy Stock problem
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int prevBuy = Integer.MAX_VALUE;
int maxSellPrice = Integer.MIN_VALUE;
for (int buyDay=0; buyDay < prices.length; buyDay++) {
int buyPrice = prices[buyDay];
if (buyPrice >= prevBuy && maxSellPrice >= buyPrice) {
continue;
}
maxSellPrice = prices[buyDay];
for (int sellDay = buyDay+1; sellDay < prices.length; sellDay++) {
maxSellPrice = Math.max(maxSellPrice, prices[sellDay]);
}
maxProfit = Math.max(maxProfit, maxSellPrice-buyPrice);
prevBuy = buyPrice;
}
return maxProfit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment