Skip to content

Commit a3bf3f1

Browse files
Optimize Maximum Fruits solution with sliding window approach to fix TLE
1 parent b3ca4d9 commit a3bf3f1

File tree

4 files changed

+66
-34
lines changed

4 files changed

+66
-34
lines changed

Hard/2025-08-03-2106-MaximumFruitsHarvestedAfterAtMostKSteps/explanation.md

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,17 +43,19 @@ Explanation:
4343

4444
**Algorithm**:
4545
1. Sort the fruits by position to get them in order.
46-
2. Use a sliding window approach to find the maximum sum of fruits that can be harvested within `k` steps.
47-
3. For each window, calculate the minimum steps needed to reach all fruits in the window.
48-
4. The minimum steps for a window from position `left` to `right` is: `right - left + min(left, right - left)`.
46+
2. Use a sliding window approach with two pointers (left and right).
47+
3. Expand the window by moving the right pointer and add fruits to the current sum.
48+
4. When the window becomes invalid (steps > k), shrink it from the left until it's valid again.
49+
5. Keep track of the maximum sum of fruits found in any valid window.
4950

5051
**Why this works**:
5152
- We need to visit all fruits in a contiguous range
5253
- The optimal path is to go to one end, then to the other end
5354
- The total steps is the distance between the two ends plus the distance from start to the closer end
55+
- Sliding window ensures we find the optimal range efficiently
5456

5557
## Complexity Analysis
56-
- **Time Complexity**: O(n log n) - Due to sorting the fruits by position
58+
- **Time Complexity**: O(n log n) - Due to sorting the fruits by position, then O(n) for sliding window
5759
- **Space Complexity**: O(1) - Only using a few variables for the sliding window
5860

5961
## Key Insights
@@ -63,9 +65,10 @@ Explanation:
6365
- Use sliding window to find the maximum sum within the step constraint
6466

6567
## Alternative Approaches
66-
1. **Brute Force**: Try all possible ranges - O(n²) time
67-
2. **Binary Search**: Can be used to optimize the sliding window approach
68-
3. **Dynamic Programming**: Can be used but overkill for this problem
68+
1. **Brute Force**: Try all possible ranges - O(n²) time (causes TLE)
69+
2. **Sliding Window**: O(n) time after sorting - optimal approach
70+
3. **Binary Search**: Can be used to optimize the sliding window approach
71+
4. **Dynamic Programming**: Can be used but overkill for this problem
6972

7073
## Solutions in Different Languages
7174

Hard/2025-08-03-2106-MaximumFruitsHarvestedAfterAtMostKSteps/solution.java

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,33 @@ public int maxTotalFruits(int[][] fruits, int startPos, int k) {
77

88
int n = fruits.length;
99
int maxFruits = 0;
10+
int left = 0;
11+
int currentSum = 0;
1012

11-
// Try all possible ranges
12-
for (int left = 0; left < n; left++) {
13-
for (int right = left; right < n; right++) {
13+
// Sliding window approach
14+
for (int right = 0; right < n; right++) {
15+
currentSum += fruits[right][1];
16+
17+
// Shrink window from left while it's invalid
18+
while (left <= right) {
1419
int leftPos = fruits[left][0];
1520
int rightPos = fruits[right][0];
1621

17-
// Calculate minimum steps needed
22+
// Calculate minimum steps needed for current window
1823
int steps = rightPos - leftPos + Math.min(Math.abs(startPos - leftPos), Math.abs(startPos - rightPos));
1924

2025
if (steps <= k) {
21-
// Calculate total fruits in this range
22-
int totalFruits = 0;
23-
for (int i = left; i <= right; i++) {
24-
totalFruits += fruits[i][1];
25-
}
26-
maxFruits = Math.max(maxFruits, totalFruits);
26+
break; // Window is valid, keep it
2727
}
28+
29+
// Remove leftmost fruit and shrink window
30+
currentSum -= fruits[left][1];
31+
left++;
32+
}
33+
34+
// Update max fruits if window is valid
35+
if (left <= right) {
36+
maxFruits = Math.max(maxFruits, currentSum);
2837
}
2938
}
3039

Hard/2025-08-03-2106-MaximumFruitsHarvestedAfterAtMostKSteps/solution.js

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,33 @@ var maxTotalFruits = function(fruits, startPos, k) {
1010

1111
const n = fruits.length;
1212
let maxFruits = 0;
13+
let left = 0;
14+
let currentSum = 0;
1315

14-
// Try all possible ranges
15-
for (let left = 0; left < n; left++) {
16-
for (let right = left; right < n; right++) {
16+
// Sliding window approach
17+
for (let right = 0; right < n; right++) {
18+
currentSum += fruits[right][1];
19+
20+
// Shrink window from left while it's invalid
21+
while (left <= right) {
1722
const leftPos = fruits[left][0];
1823
const rightPos = fruits[right][0];
1924

20-
// Calculate minimum steps needed
25+
// Calculate minimum steps needed for current window
2126
const steps = rightPos - leftPos + Math.min(Math.abs(startPos - leftPos), Math.abs(startPos - rightPos));
2227

2328
if (steps <= k) {
24-
// Calculate total fruits in this range
25-
let totalFruits = 0;
26-
for (let i = left; i <= right; i++) {
27-
totalFruits += fruits[i][1];
28-
}
29-
maxFruits = Math.max(maxFruits, totalFruits);
29+
break; // Window is valid, keep it
3030
}
31+
32+
// Remove leftmost fruit and shrink window
33+
currentSum -= fruits[left][1];
34+
left++;
35+
}
36+
37+
// Update max fruits if window is valid
38+
if (left <= right) {
39+
maxFruits = Math.max(maxFruits, currentSum);
3140
}
3241
}
3342

Hard/2025-08-03-2106-MaximumFruitsHarvestedAfterAtMostKSteps/solution.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,30 @@ def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
77

88
n = len(fruits)
99
max_fruits = 0
10+
left = 0
11+
current_sum = 0
1012

11-
# Try all possible ranges
12-
for left in range(n):
13-
for right in range(left, n):
13+
# Sliding window approach
14+
for right in range(n):
15+
current_sum += fruits[right][1]
16+
17+
# Shrink window from left while it's invalid
18+
while left <= right:
1419
left_pos = fruits[left][0]
1520
right_pos = fruits[right][0]
1621

17-
# Calculate minimum steps needed
22+
# Calculate minimum steps needed for current window
1823
steps = right_pos - left_pos + min(abs(startPos - left_pos), abs(startPos - right_pos))
1924

2025
if steps <= k:
21-
# Calculate total fruits in this range
22-
total_fruits = sum(fruits[i][1] for i in range(left, right + 1))
23-
max_fruits = max(max_fruits, total_fruits)
26+
break # Window is valid, keep it
27+
28+
# Remove leftmost fruit and shrink window
29+
current_sum -= fruits[left][1]
30+
left += 1
31+
32+
# Update max fruits if window is valid
33+
if left <= right:
34+
max_fruits = max(max_fruits, current_sum)
2435

2536
return max_fruits

0 commit comments

Comments
 (0)