122. Best Time to Buy and Sell Stock II [Leetcode][C++]

mayankdv

Mayank Arora

Posted on December 24, 2021

122. Best Time to Buy and Sell Stock II [Leetcode][C++]

All suggestions are welcome. Please upvote if you like it. Thank you.


Leetcode Problem Link: 122. Best Time to Buy and Sell Stock II


e.g. Array=[7,1,5,3,6,4]
Image description
Valley to Peak approach : Add all gains from positive slopes i.e. profit = (5-1) + (6-3) = 7

Efficient Solution:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // Optimal Solution Time O(N) & Auxiliary Space O(1)
        int res = 0;
        for (int i = 1; i < prices.size(); ++i)
            res += max(prices[i] - prices[i - 1], 0);
        return res;
    }
};
Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

💖 💪 🙅 🚩
mayankdv
Mayank Arora

Posted on December 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related