121. Best Time to Buy and Sell Stock (Leetcode)

PHOTO EMBED

Wed Oct 06 2021 08:57:16 GMT+0000 (UTC)

Saved by @Sakshamkashyap7 #c++

// TC - O(n) || SC - O(1)
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size() - 1, ans = 0, minSoFar = INT_MAX;
        for(int i = 0; i < n; ++i)  {
            minSoFar = min(minSoFar, prices[i]);
            ans = max(ans, (prices[i] - minSoFar));
        }
        return ans;
    }
};

// we can use auxilary array and store maxSoFar value
content_copyCOPY

Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/