πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- 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;
	}
}