titan2400

Best Time to Buy and Sell Stock - LeetCode

Nov 5th, 2025
738
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | Source Code | 0 0
  1. // Best Time to Buy and Sell Stock - https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
  2.  
  3. class Solution {
  4.     // Brute Force
  5.     // Time Complexity: O(n^2)
  6.     // Space Complexity: O(1)
  7.     // Below brute force solution leads to Time Limit Exceeded on LeetCode
  8.     // public int maxProfit(int[] prices) {
  9.     //     int maxP = 0;
  10.     //         for(int i = 0; i < prices.length; i++) {
  11.     //             int curMax = 0;
  12.     //             for(int j = i + 1; j < prices.length; j++) {
  13.     //                 int profit = prices[j] - prices[i];
  14.     //                 if(profit > curMax) {
  15.     //                     curMax = profit;
  16.     //                 }
  17.     //             }
  18.     //             maxP = Math.max(maxP, curMax);
  19.     //         }
  20.     //     return maxP;
  21.     // }
  22.  
  23.     // Two Pointers (Sliding Window)
  24.     // Time Complexity: O(n)
  25.     // Space Complexity: O(1)
  26.     // public int maxProfit(int[] prices) {
  27.         // int maxP = 0;
  28.         // int l = 0, r = 1;
  29.         // while(r < prices.length) {
  30.             // if(prices[l] < prices[r]) {
  31.                 // int profit = prices[r] - prices[l];
  32.                 // maxP = Math.max(maxP, profit);
  33.             // }
  34.             // else {
  35.                 // l = r;
  36.             // }
  37.             // r++;
  38.         // }
  39.         // return maxP;
  40.     // }
  41.  
  42.  
  43.  
  44.     // Dynamic Programming
  45.     // Time Complexity: O(n)
  46.     // Space Complexity: O(1)
  47.     public int maxProfit(int[] prices) {
  48.         int maxP = 0;
  49.         int minSoFar = Integer.MAX_VALUE;
  50.         for(int i = 0; i < prices.length; i++) {
  51.             int curMax = prices[i] - minSoFar;
  52.             maxP = Math.max(maxP, curMax);
  53.             minSoFar = Math.min(minSoFar, prices[i]);
  54.         }
  55.         return maxP;
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment