LeetCode 2106: Maximum Fruits Harvested After at Most K Steps Solution
Master LeetCode problem 2106 (Maximum Fruits Harvested After at Most K Steps), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2106. Maximum Fruits Harvested After at Most K Steps
Problem Explanation
Explanation
To solve this problem, we can use a sliding window approach. We will maintain a window of size k starting from the startPos position and keep track of the maximum fruits harvested within this window. We will iteratively expand the window by moving left or right based on which direction gives us more fruits until we have taken k steps.
We will use a hashmap to store the positions of fruits along with the number of fruits at each position for efficient lookup. We will also keep track of the total fruits harvested so far.
Time complexity: O(n) where n is the number of elements in the fruits array
Space complexity: O(n) for the hashmap
Solution Code
import java.util.*;
class Solution {
public int maxFruits(int[][] fruits, int startPos, int k) {
Map<Integer, Integer> fruitMap = new HashMap<>();
int fruitsHarvested = 0;
int maxFruits = 0;
int left = startPos;
int right = startPos;
for (int[] fruit : fruits) {
fruitMap.put(fruit[0], fruit[1]);
}
while (k > 0) {
if (fruitMap.containsKey(left)) {
fruitsHarvested += fruitMap.get(left);
maxFruits = Math.max(maxFruits, fruitsHarvested);
k--;
left--;
} else if (fruitMap.containsKey(right)) {
fruitsHarvested += fruitMap.get(right);
maxFruits = Math.max(maxFruits, fruitsHarvested);
k--;
right++;
} else {
if (left == startPos && right == startPos) {
break;
}
if (left > 0) {
left--;
}
if (right < 2 * 105) {
right++;
}
}
}
return maxFruits;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2106 (Maximum Fruits Harvested After at Most K Steps)?
This page provides optimized solutions for LeetCode problem 2106 (Maximum Fruits Harvested After at Most K Steps) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2106 (Maximum Fruits Harvested After at Most K Steps)?
The time complexity for LeetCode 2106 (Maximum Fruits Harvested After at Most K Steps) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2106 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2106 in Java, C++, or Python.