|
| 1 | +/** |
| 2 | + * 2106. Maximum Fruits Harvested After at Most K Steps |
| 3 | + * https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array |
| 7 | + * fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. |
| 8 | + * fruits is already sorted by positioni in ascending order, and each positioni is unique. |
| 9 | + * |
| 10 | + * You are also given an integer startPos and an integer k. Initially, you are at the position |
| 11 | + * startPos. From any position, you can either walk to the left or right. It takes one step to |
| 12 | + * move one unit on the x-axis, and you can walk at most k steps in total. For every position |
| 13 | + * you reach, you harvest all the fruits at that position, and the fruits will disappear from |
| 14 | + * that position. |
| 15 | + * |
| 16 | + * Return the maximum total number of fruits you can harvest. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number[][]} fruits |
| 21 | + * @param {number} startPos |
| 22 | + * @param {number} k |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var maxTotalFruits = function(fruits, startPos, k) { |
| 26 | + let result = 0; |
| 27 | + let left = 0; |
| 28 | + let currentSum = 0; |
| 29 | + |
| 30 | + for (let right = 0; right < fruits.length; right++) { |
| 31 | + currentSum += fruits[right][1]; |
| 32 | + |
| 33 | + while (left <= right) { |
| 34 | + const minPos = fruits[left][0]; |
| 35 | + const maxPos = fruits[right][0]; |
| 36 | + const steps = Math.min( |
| 37 | + Math.abs(startPos - minPos) + (maxPos - minPos), |
| 38 | + Math.abs(startPos - maxPos) + (maxPos - minPos) |
| 39 | + ); |
| 40 | + |
| 41 | + if (steps <= k) break; |
| 42 | + currentSum -= fruits[left][1]; |
| 43 | + left++; |
| 44 | + } |
| 45 | + |
| 46 | + if (left <= right) { |
| 47 | + result = Math.max(result, currentSum); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return result; |
| 52 | +}; |
0 commit comments