LeetCode: Best time to buy and sell stocks

Problem statements:

Examples:

Constraints:

Edge cases to consider

Brute-Force Approach: [T.C. - O(n2)O(n^2), S.C. - O(1)O(1)]

Algorithm for Brute-Force Approach:

Brute-Force: Java implementation

    class SolutionBruteForce {
        public int maxProfit(int[] prices) {
            int n = prices.length;
            int maxProfit = 0;
            for (int i = 0; i < n - 1; i++) {
                for (int j = i + 1; j < n; j++) {
                    int profit = prices[j] - prices[i];
                    if (profit > maxProfit) {
                        maxProfit = profit;
                    }
                }
            }
            return maxProfit;
        }
    }

Brute-Force: Python implementation

      def max_profit_brute_force(prices):
        n = len(prices)
        max_profit = 0
        for i in range(n - 1):
            for j in range(i + 1, n):
                profit = prices[j] - prices[i]
                if profit > max_profit:
                    max_profit = profit
        return max_profit

Optimized Approach:

Solution: Two pointer approach

Algorithm for Optimized Approach [T.C: $$O(n), S.C: O(1)O(1)]:

Two poiner : Java implementation

    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            minPrice = Math.min(minPrice, price);
            int profit = price - minPrice;
            maxProfit = Math.max(maxProfit, profit);
        }
        return maxProfit;
    }

    //implementation 2
    public int maxProfit(int[] prices) {
      
      if(prices.length <= 1) return 0;
      
      int profit = 0, l = 0, r = l + 1;
      while(r < prices.length) {
          if(prices[l] < prices[r]) {
              int t = prices[r] - prices[l];
              profit = profit > t ? profit : t;
              r++;
          } else {
              l = r;
              r++;
          }
      }
      return profit;
  }

Two poiner : Python implementation

    def max_profit_optimized(prices):
      min_price = float('inf')
      max_profit = 0
      for price in prices:
          min_price = min(min_price, price)
          profit = price - min_price
          max_profit = max(max_profit, profit)
      return max_profit

------ End ------