-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathProblem_4_FruitsIntoBasket.java
More file actions
26 lines (23 loc) · 1007 Bytes
/
Problem_4_FruitsIntoBasket.java
File metadata and controls
26 lines (23 loc) · 1007 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package Sliding_Window;
// Problem Statement: Fruits into Baskets (medium)
// LeetCode Question: 904. Fruit Into Baskets
import java.util.HashMap;
import java.util.Map;
public class Problem_4_FruitsIntoBasket {
public int totalFruit(char[] arr){
int windowStart = 0, maxLength = 0;
Map<Character, Integer> fruitFrequencyMap = new HashMap<>();
for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
fruitFrequencyMap.put(arr[windowEnd], fruitFrequencyMap.getOrDefault(arr[windowEnd], 0) + 1);
while(fruitFrequencyMap.size() > 2){
fruitFrequencyMap.put(arr[windowStart], fruitFrequencyMap.get(arr[windowStart]) - 1);
if (fruitFrequencyMap.get(arr[windowStart]) == 0) {
fruitFrequencyMap.remove(arr[windowStart]);
}
windowStart++;
}
maxLength = Math.max(maxLength, windowEnd - windowStart + 1);
}
return maxLength;
}
}