122. Best Time to Buy and Sell Stock II
View on LeetCode ↗
C++
class Solution {public: int maxProfit(vector<int>& prices) { std::vector<int> changes; int sum = 0; for (int i = 0; i < prices.size() - 1; i++) { if (prices[i + 1] - prices[i] > 0) { sum += prices[i + 1] - prices[i]; } } return sum; }};
light work, just look at changes and do bare minimum of what the question is asking. just get positive changes and sum such up for max profit. greedy part was to conditionally chose positive profit.