We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Best Time to Buy and Sell Stock II

Number: 122

Difficulty: Medium

Paid? No

Companies: Amazon, Google, Meta, Bloomberg, Goldman Sachs, Microsoft, Apple, Walmart Labs, Paytm, Infosys, Zoho, CTC, Adobe, TikTok, Citadel, Yahoo, DE Shaw, Qualcomm, Intel, Accenture, Wells Fargo, Media.net, Groww


Problem Description

Given an array of stock prices where prices[i] is the price on the i-th day, determine the maximum profit that can be achieved. You can buy and sell multiple times; however, you can hold at most one share at any time. Transactions on the same day (buy and sell on the same day) are allowed.


Key Insights

  • You can make as many transactions as needed as long as you are not holding more than one share.
  • The best strategy is to capture every upward movement in price.
  • Instead of finding the best pair of days for each transaction, sum the differences between consecutive days that indicate an increase.
  • This greedy approach avoids complex dynamic programming structures while still ensuring maximum profit.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the prices array, since we traverse the list once. Space Complexity: O(1), as we only need a few integer variables for tracking profit.


Solution

The solution uses a greedy approach by iterating over the prices list and adding up profits each time there is a rise from one day to the next. If prices[i] is lower than prices[i+1], buying on day i and selling on day i+1 will add to the overall profit. The idea is that accumulating all these small profits yields the maximum profit possible by making as many transactions as necessary. The approach avoids explicit tracking of all transactions, requiring only constant extra space.


Code Solutions

# Function to calculate maximum profit
def maxProfit(prices):
    profit = 0
    # Iterate over the price list starting from the first day
    for i in range(1, len(prices)):
        # If there is a rise in price from previous day, add up the profit
        if prices[i] > prices[i - 1]:
            profit += prices[i] - prices[i - 1]
    return profit

# Example usage:
prices = [7,1,5,3,6,4]
print(maxProfit(prices))  # Output: 7
← Back to All Questions