Ctrl K

Berry Walk Along a Path

Hard
Berry bushes grow along an endless straight path. You are given a list bushes, where bushes[i] = [position, amount] means amount berries grow at point position. The list is sorted by position in increasing order, and all positions are distinct. You stand at point start and may take at most steps steps. A step moves you one unit left or right, and you may change direction as often as you like. At every point you visit (including start) you pick all the berries; they do not grow back. Return the largest number of berries you can pick.
Example 1
bushes=[[1, 4], [3, 2], [9, 5]], start=4, steps=5 → 6

Walk left: position 3 (2 berries), then position 1 (4 berries), 3 steps for 6 berries. Reaching position 9 takes 5 steps and yields only 5.

Example 2
bushes=[[2, 3], [5, 1], [8, 6]], start=5, steps=6 → 7

Walk right to 8: 3 steps for 1 + 6 = 7 berries. Getting from there to 2 would take 6 more steps, which you do not have. Going left to 2 and back gives only 3 + 1 = 4.

Example 3
bushes=[[10, 7]], start=0, steps=3 → 0
Constraints
  • 1 ≤ len(bushes) ≤ 10⁵
  • bushes[i] = [position, amount]
  • 0 ≤ start, position ≤ 2·10⁵
  • positions are strictly increasing
  • 1 ≤ amount ≤ 10⁴
  • 0 ≤ steps ≤ 2·10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Stretch Reaching a Total HardSum Times Length Under a Limit HardLongest Affordable Run of Machines HardSignal in the Remotest Village HardMost Equal Values on a Budget Hard
loading Python…
Input
bushes=[[1, 4], [3, 2], [9, 5]], start=4, steps=5
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.