Maximum Fruits Harvested After at Most K Steps

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
Inputfruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4
Output9
The optimal way is to move right to positions 6 and 8, harvesting 3 + 6 = 9 fruits in 3 steps.
Example 2
Inputfruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4
Output14
The optimal reachable route harvests fruits at positions 5, 4, 6, and 7 for a total of 7 + 1 + 2 + 4 = 14 fruits in 4 steps.

Constraints

  • 1 <= fruits.length <= 10^5
  • fruits[i].length == 2
  • 0 <= startPos, positioni <= 2 * 10^5
  • positioni-1 < positioni for any i > 0 (0-indexed)
  • 1 <= amounti <= 10^4
  • 0 <= k <= 2 * 10^5

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate