Advertisement

Maximum Fruits Harvested After at Most K Steps - LeetCode 2106 Solution

Maximum Fruits Harvested After at Most K Steps - Complete Solution Guide

Maximum Fruits Harvested After at Most K Steps is LeetCode problem 2106, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [position i , amount i ] depicts amount i fruits at the position position i . fruits is already sorted by position i in ascending order , and each position i 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-

Detailed Explanation

The problem asks us to find the maximum number of fruits we can harvest given a sorted list of fruit locations and amounts, a starting position, and a maximum number of steps (k). We can move left or right from our starting position and harvest all fruits at a given position. The goal is to maximize the total fruits harvested within the step limit.

Solution Approach

The solution uses a sliding window approach to explore different ranges of fruits. For each window, the cost (number of steps) to visit all fruits within the window is calculated. If the cost is within the limit (k), the total fruits in that window is considered as a potential maximum. The sliding window expands to the right, and the left boundary shifts right when the cost exceeds k. The maximum fruit count is updated during the sliding process.

Step-by-Step Algorithm

  1. Step 1: Initialize `max_fruits` to 0, `left_ptr` to 0, and `current_sum` to 0.
  2. Step 2: Iterate through the `fruits` array with `right_ptr` from 0 to n-1.
  3. Step 3: Add the amount of fruits at `fruits[right_ptr]` to `current_sum`.
  4. Step 4: While the cost to travel from `fruits[left_ptr]` to `fruits[right_ptr]` exceeds `k`, subtract the amount of fruits at `fruits[left_ptr]` from `current_sum` and increment `left_ptr`.
  5. Step 5: Update `max_fruits` to the maximum of its current value and `current_sum`.
  6. Step 6: Return `max_fruits`.

Key Insights

  • Insight 1: The 'fruits' array is sorted, making a sliding window approach viable.
  • Insight 2: We need to efficiently calculate the cost (number of steps) to reach a range of fruits, considering the possible routes: all left, all right, or a combination of left and right, and vice-versa.
  • Insight 3: Prefix sum can be used for efficient retrieval of the sum of fruits within the sliding window.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Array, Binary Search, Sliding Window, Prefix Sum.

Companies

Asked at: Deutsche Bank.