[LeetCode] Maximum Fruits Harvested After at Most K Steps

2106. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int maxTotalFruits(vector<vector<int>>& f, int startPos, int k) {
int st = startPos - k;
int l = 0, r = 0, n = f.size(), res = 0, sum = 0;
while(l < n and f[l][0] < st) l++;
r = l;
while(l < n and r < n and f[r][0] <= startPos + k) {
sum += f[r][1];
while(k < min(startPos - 2 * f[l][0] + f[r][0], 2 * f[r][0] - f[l][0] - startPos))
sum -= f[l++][1];

res = max(res, sum);
r++;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/22/PS/LeetCode/maximum-fruits-harvested-after-at-most-k-steps/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.