Best Time to Sell Stock II [Greedy]
def maxProfit(prices):
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++)
if (prices[i] > prices[i - 1])
profit += prices[i] - prices[i - 1];
return profit;
}
}
class Solution {
public:
int maxProfit(vector& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++)
if (prices[i] > prices[i - 1])
profit += prices[i] - prices[i - 1];
return profit;
}
};
Problem Statement
You are given an array prices where prices[i] is the price of a given stock on the ith day. Design an algorithm to find the maximum profit by buying and selling the stock multiple times. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: you must sell the stock before you buy again.
Detailed Explanation
Approach
The solution uses a greedy approach by capturing every possible profit opportunity. If the price tomorrow is higher than today, we buy today and sell tomorrow. This approach works because we can break down any profitable sequence into a series of daily profits.
Key Concepts
- Valley-Peak Approach: Buy at every valley and sell at every peak
- Daily Profits: Capture every positive price difference between consecutive days
- Multiple Transactions: Can buy immediately after selling
Algorithm Steps
- Initialize total profit as 0
- Iterate through prices starting from index 1:
- If current price is higher than previous price
- Add the difference to total profit
- Return total accumulated profit
Visual Example
Time and Space Complexity
- Time Complexity: O(n) - Single pass through the array
- Space Complexity: O(1) - Only using one variable
Why This Works
This approach works because any profitable sequence can be broken down into a series of profitable one-day transactions. For example, if we can profit by buying on day 1 and selling on day 4, this is equivalent to buying on day 1, selling on day 2, buying on day 2, selling on day 3, and so on up to day 4 (if each consecutive day has a higher price).
Edge Cases
- Array length ≤ 1: Return 0
- Prices always decreasing: Return 0
- All prices same: Return 0
- Single valley-peak: Return their difference
Common Mistakes
- Trying to track actual buy/sell days
- Over-complicating with valley-peak tracking
- Not realizing you can sell and buy on the same day
- Missing the fact that capturing all positive differences is optimal