InterviewHubPRO
Section Overview
Q12

Question 12 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

12%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Best Time to Buy and Sell Stock (I & II).

In Simple Words:

  • Part I (One Transaction): Track minPrice seen so far and update maxProfit = max(maxProfit, price - minPrice).
  • Part II (Unlimited Transactions): Accumulate all positive price differences price[i] - price[i-1] greedily.
  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def maxProfitPartI(prices: list[int]) -> int:
    min_price = float('inf')
    max_p = 0
    for p in prices:
        min_price = min(min_price, p)
        max_p = max(max_p, p - min_price)
    return max_p

def maxProfitPartII(prices: list[int]) -> int:
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]:
            profit += prices[i] - prices[i - 1]
    return profit