Taro Logo

Maximum Fruits Harvested After at Most K Steps

Hard
Asked by:
Profile picture
Profile picture
3 views
Topics:
ArraysTwo PointersBinary SearchSliding Windows

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 <= 105
  • fruits[i].length == 2
  • 0 <= startPos, positioni <= 2 * 105
  • positioni-1 < positioni for any i > 0 (0-indexed)
  • 1 <= amounti <= 104
  • 0 <= k <= 2 * 105

Solution


Clarifying Questions

When 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:

  1. Are the fruit positions in the 2D array guaranteed to be given in sorted order, or could they be unsorted?
  2. Can multiple fruit entries exist at the exact same position on the number line, and if so, should their amounts be combined?
  3. What is the range of values for the coordinates, the amount of fruits, the starting position `startPos`, and the step limit `k`?
  4. Can `startPos` be located completely outside the range of the given fruit positions?
  5. If no fruits can be harvested within the `k` step limit, should the function return 0?

Brute Force Solution

Approach

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:

  1. Begin by identifying every possible direction and distance you could walk while staying within your allowed total steps.
  2. For your first trial, imagine walking a certain distance to the left and then turning around to walk a certain distance to the right, as long as the total walking cost does not exceed your limit.
  3. Count up all the fruit you would collect along this specific path.
  4. Next, try the opposite pattern by walking a certain distance to the right first and then turning back to the left, again making sure you do not run out of steps.
  5. Count the fruit collected on this new path as well.
  6. Repeat this trial-and-error process for every possible combination of left and right movements that fit inside your maximum allowed steps.
  7. Compare the fruit totals from every single path you tested.
  8. Declare the winning path as the one that allowed you to gather the highest total amount of fruit.

Code Implementation

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_found

Big(O) Analysis

Time Complexity
O(n²) – The brute force strategy evaluates every possible combination of walking left first or right first within the step limit across the n fruit positions. For each starting direction and distance, we iterate through the corresponding fruit trees to count the harvested amount. This trial-and-error process tests approximately n different turning points, and for each turning point, we check up to n fruit locations. This results in roughly n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute-force trial-and-error approach described in the plain English steps requires only a few primitive integer variables to track the current walking boundaries, step limits, and fruit counts. No auxiliary data structures, temporary lists, or recursion stack frames scale with the input size N, which represents the number of fruit tree positions. Therefore, the extra memory usage remains completely constant regardless of how many fruit trees or steps are evaluated.

Optimal Solution

Approach

Instead 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:

  1. Picture the line of trees stretching out with different amounts of fruit growing at various positions.
  2. Stand at your starting position, which is where you begin counting your allowed walking steps.
  3. Imagine casting a flexible window over a section of trees that you can fully explore without running out of steps.
  4. Start expanding the right side of your window to include more trees and tally up all the fruit inside.
  5. Whenever extending the right side causes your total steps to exceed your allowed limit, slide the left side of your window forward to drop some trees and save steps.
  6. Constantly keep track of the total fruit collected inside your valid window as it slides and stretches across the path.
  7. Stop when the right side of your window reaches the very end of the fruit line, and the maximum fruit you ever held in your window is your winning answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – The sliding window strategy expands the right boundary across the array of fruit positions while conditionally advancing the left boundary when the step limit is exceeded. Both the right and left pointers only move forward and never backtrack across the fruit line. Because each of the n fruit positions is visited at most once by the right pointer and at most once by the left pointer, the total operations scale linearly with the number of elements. Thus, the work simplifies directly to O(n) time complexity.
Space Complexity
O(1) – The sliding window strategy only requires a few primitive integer variables to keep track of the left and right boundaries, the current fruit sum, and the maximum fruits collected. These variables track positions along the existing fruit line without duplicating data or creating dynamic structures. Since no auxiliary arrays, hash maps, or recursive call stacks are allocated, the memory footprint remains constant regardless of the number of fruit positions or the step limit K. Therefore, the auxiliary space complexity simplifies to Big O of 1.

Edge Cases

Empty fruit array or zero steps allowed while starting at zero fruits
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Accumulate the fruit sums using 64-bit integer types to prevent integer overflow.