- best to take a greedy approach where we only buy stock when we know that a profit can be made
- we can ignore potential trades that will incur a loss
- To maximize profit over multiple transactions, we aim to capture every upward price movement (whenever prices[i+1]>prices[i]prices[i+1] > prices[i]prices[i+1]>prices[i]).
π€What Did I Struggle With?
~
π‘ Explanation of Solution
To maximize profit over multiple transactions, we aim to capture every upward price movement (whenever prices[i+1]>prices[i]prices[i+1] > prices[i]prices[i+1]>prices[i]).
This is equivalent to summing up all positive differences between consecutive prices.
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
π» Implementation of Solution
class Solution {public: int maxProfit(vector<int>& prices) { int totalProfit = 0; for(int i = 1; i < prices.size(); i++) { if(prices[i] > prices[i - 1]) { totalProfit = prices[i] - prices[i - 1]; } } return totalProfit; }}