Advertisement
MuzammiL5

Buy Sell Stocks

Jun 3rd, 2023 (edited)
998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.43 KB | None | 0 0
  1. // Greedy Approach: Iterate through the prices and maintain buy price and maxprofit gained up until that point. -> O(N), O(1)
  2. int maxProfit(int[] prices, int n) {
  3.     int buy = prices[0], max_profit = 0;
  4.     for (int i=1; i<n; i++) {
  5.         if (buy > prices[i]) {
  6.             buy = prices[i];
  7.         } else if (prices[i] - buy > max_profit) {
  8.             max_profit = prices[i] - buy;
  9.         }
  10.     }
  11.     return max_profit;
  12. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement