Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.
You are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.
Return the maximum total number of fruits you can harvest.
Example 1:
Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4 Output: 9 Explanation: The optimal way is to: - Move right to position 6 and harvest 3 fruits - Move right to position 8 and harvest 6 fruits You moved 3 steps and harvested 3 + 6 = 9 fruits in total.
Example 2:
Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4 Output: 14 Explanation: You can move at most k = 4 steps, so you cannot reach position 0 nor 10. The optimal way is to: - Harvest the 7 fruits at the starting position 5 - Move left to position 4 and harvest 1 fruit - Move right to position 6 and harvest 2 fruits - Move right to position 7 and harvest 4 fruits You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.
Example 3:
Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2 Output: 0 Explanation: You can move at most k = 2 steps and cannot reach any position with fruits.
Constraints:
1 <= fruits.length <= 105fruits[i].length == 20 <= startPos, positioni <= 2 * 105positioni-1 < positioni for any i > 0 (0-indexed)1 <= amounti <= 1040 <= k <= 2 * 105When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are standing at a starting spot on a long line of fruit trees and you can only take a limited number of steps in total. The brute force approach involves trying out every single possible walking path you could possibly take within your step limit, gathering all the fruit along each path.
Here's how the algorithm would work step-by-step:
def max_total_fruits(fruits, start_position, step_limit):
maximum_fruits_found = 0
# Iterate through all possible starting positions to check every possible interval of trees
for left_boundary in range(len(fruits)):
for right_boundary in range(left_boundary, len(fruits)):
left_position = fruits[left_boundary][0]
right_position = fruits[right_boundary][0]
distance_left_first = abs(start_position - left_position) + (right_position - left_position)
distance_right_first = abs(start_position - right_position) + (right_position - left_position)
# Verify if the chosen path interval can be traversed within the allowed step limit
if min(distance_left_first, distance_right_first) <= step_limit:
current_fruit_sum = sum(amount for position, amount in fruits[left_boundary:right_boundary + 1])
maximum_fruits_found = max(maximum_fruits_found, current_fruit_sum)
# Return the maximum harvested fruits found across all valid paths tested within the step budget
return maximum_fruits_foundInstead of testing every possible walking path to gather fruits within your limited steps, you can use a sliding window strategy to keep track of a reachable span of positions. As you move the right boundary of your range further down the path, you adjust the left boundary to ensure your total steps needed remain within your limit, always aiming to maximize the delicious items collected inside your current window.
Here's how the algorithm would work step-by-step:
class Solution:n def maxTotalFruits(self, fruits: list[list[int]], start_position: int, max_steps: int) -> int:n left_boundary = 0n maximum_fruits = 0n current_fruits_sum = 0n n # Expand the window to the right while maintaining the sliding window boundaries.n for right_boundary in range(len(fruits)):
current_fruits_sum += fruits[right_boundary][1]
# Shrink the window from the left if the total steps needed exceed the allowed limit.n while left_boundary <= right_boundary and not (
abs(fruits[right_boundary][0] - start_position) + abs(fruits[left_boundary][0] - start_position) + min(abs(fruits[right_boundary][0] - start_position), abs(fruits[left_boundary][0] - start_position)) <= max_steps
):
current_fruits_sum -= fruits[left_boundary][1]
left_boundary += 1
# Track the maximum amount of fruit collected within any valid window.n if current_fruits_sum > maximum_fruits:
maximum_fruits = current_fruits_sum
return maximum_fruits| Case | How to Handle |
|---|---|
| Empty fruit array or zero steps allowed while starting at zero fruits | Return zero immediately as no fruits can be harvested under these constraints. |
| All fruits are located entirely outside the reachable range defined by the starting position and k steps | The sliding window will not find any valid intervals and will naturally return zero. |
| Multiple fruit entries share the exact same coordinate position on the number line | The initial preprocessing or coordinate mapping should sum amounts at identical positions to prevent index mismatch. |
| Starting position is far away from all fruits, but k is large enough to reach them in one direction | The sliding window approach will expand fully in the reachable direction and correctly capture all available fruits. |
| Large coordinate values exceeding standard integer limits or sparse fruit distributions | Using prefix sums over a coordinate-compressed or bounded array prevents out-of-memory errors and handles large spaces efficiently. |
| Turning around strategy where optimal path involves moving in one direction first and then reversing | The sliding window correctly evaluates both left-then-right and right-then-left turn configurations within k steps. |
| Total amount of fruits exceeds standard 32-bit integer capacity | Accumulate the fruit sums using 64-bit integer types to prevent integer overflow. |