You are given an integer array prices where prices[i] is the price of a given stock on the ( i )-th day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
To maximize profit, you want to take advantage of all price rises. You can achieve this by adding up all positive differences between consecutive days. Thus, the strategy is:
This greedy strategy works because any accumulated positive differences will represent profitable transactions.
def maxProfit(prices):
total_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
total_profit += prices[i] - prices[i - 1]
return total_profit
# Example Usage
print(maxProfit([7, 1, 5, 3, 6, 4])) # Output: 7
print(maxProfit([1, 2, 3, 4, 5])) # Output: 4
print(maxProfit([7, 6, 4, 3, 1])) # Output: 0
The time complexity of this algorithm is ( O(n) ), where ( n ) is the length of the prices array. This is because the solution involves a single pass through the array, making comparisons and additions for each day.
The space complexity is ( O(1) ), as we are only using a constant amount of extra space for the total profit variable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?