#3652

Best Time to Buy and Sell Stock using Strategy

Medium
ArraySliding WindowPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use prefix sums to quickly calculate profits and deltas for segments of length k, allowing us to efficiently find the maximum profit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the base profit using prefix sums for prices and strategy.
  2. 2Step 2: Iterate through each possible segment of length k, calculating the profit delta using precomputed sums.
  3. 3Step 3: Update the maximum profit based on the base profit and the best delta found.
solution.py9 lines
1def maxProfit(prices, strategy, k):
2    n = len(prices)
3    base_profit = sum(strategy[i] * prices[i] for i in range(n))
4    prefix_prices = [0] + list(itertools.accumulate(prices))
5    max_profit = base_profit
6    for i in range(n - k + 1):
7        delta = -prefix_prices[i + k // 2] + prefix_prices[i] + prefix_prices[i + k] - prefix_prices[i + k // 2]
8        max_profit = max(max_profit, base_profit + delta)
9    return max_profit

Complexity note: Using prefix sums allows us to compute ranges in constant time, reducing the overall complexity to O(n).

  • 1Prefix sums allow for efficient range calculations.
  • 2Understanding the impact of modifications is crucial for maximizing profit.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.