DEV Community

Mayank Arora
Mayank Arora

Posted on

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.

Top comments (0)