- Get link
- X
- Other Apps
121. Best Time to Buy and Sell Stock
Intuition
Best time of buy is as low as possible and sell it on the it is high price
Approach
Start with let if we buy on first date and check for 2nd day if the stoke price is lower in second day change the buy day to second and else find the max sell price
Complexity
- Time complexity: O(n)
- Space complexity: O(1)
Code
Java
class Solution {
public int maxProfit(int[] prices) {
int max=0;
int buy=prices[0];
for (int i = 0; i< prices.length ; i++){
if ( prices[i] > buy){
max = Math.max(max , (prices[i] - buy));
}
else{
buy = prices[i];
}
}
return max;
}
}- Get link
- X
- Other Apps
Comments
Post a Comment