#2106
Maximum Fruits Harvested After at Most K Steps
HardArrayBinary SearchSliding WindowPrefix SumSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the observation that the best path can only turn once. We can use a sliding window approach to efficiently calculate the maximum fruits harvested by considering all possible left and right movements.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, one for the leftmost position and one for the rightmost position, starting from the initial position.
- 2Step 2: Expand the right pointer to include fruits within the allowed steps, updating the total fruits harvested.
- 3Step 3: If the total steps exceed k, move the left pointer to reduce the steps, adjusting the total fruits harvested accordingly.
- 4Step 4: Keep track of the maximum fruits harvested during this process.
solution.py21 lines
1def maxFruits(fruits, startPos, k):
2 left = 0
3 right = 0
4 max_fruits = 0
5 total_fruits = 0
6 n = len(fruits)
7 while right < n:
8 # Move right pointer
9 while right < n and (fruits[right][0] <= startPos + k):
10 total_fruits += fruits[right][1]
11 right += 1
12 # Check if we need to move left pointer
13 while left < right and (startPos - fruits[left][0] > k):
14 total_fruits -= fruits[left][1]
15 left += 1
16 max_fruits = max(max_fruits, total_fruits)
17 # Move left pointer if necessary
18 if left < right:
19 total_fruits -= fruits[left][1]
20 left += 1
21 return max_fruitsℹ
Complexity note: The time complexity is O(n) because we only traverse the fruits array once with the two pointers, making it efficient.
- 1The optimal path can only turn once, which simplifies the problem significantly.
- 2Using a sliding window approach allows us to efficiently calculate the maximum fruits harvested.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.