Created
September 29, 2022 00:28
-
-
Save adeekshith/8703b6dd1dd02dbb639a9c3ce209e96c to your computer and use it in GitHub Desktop.
121. Best time to buy Stock problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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