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;
        
    }
}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50