Skip to content

Commit e0a9a28

Browse files
Update README.md
1 parent 57d33e8 commit e0a9a28

File tree

1 file changed

+56
-1
lines changed
  • solution/3400-3499/3480.Maximize Subarrays After Removing One Conflicting Pair

1 file changed

+56
-1
lines changed

solution/3400-3499/3480.Maximize Subarrays After Removing One Conflicting Pair/README.md

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,62 @@ tags:
9696

9797
```java
9898

99-
```
99+
import java.util.*;
100+
101+
class Solution {
102+
public long maxSubarrays(int n, int[][] conflictingPairs) {
103+
long maxValid = 0;
104+
105+
for (int skip = 0; skip < conflictingPairs.length; skip++) {
106+
// Build conflict map after skipping one conflicting pair
107+
Map<Integer, Set<Integer>> conflictMap = new HashMap<>();
108+
for (int i = 0; i < conflictingPairs.length; i++) {
109+
if (i == skip) continue;
110+
int a = conflictingPairs[i][0];
111+
int b = conflictingPairs[i][1];
112+
conflictMap.computeIfAbsent(a, k -> new HashSet<>()).add(b);
113+
conflictMap.computeIfAbsent(b, k -> new HashSet<>()).add(a);
114+
}
115+
116+
// Sliding window
117+
Map<Integer, Integer> freq = new HashMap<>();
118+
int left = 1;
119+
long valid = 0;
120+
121+
for (int right = 1; right <= n; right++) {
122+
freq.put(right, freq.getOrDefault(right, 0) + 1);
123+
124+
// Shrink window if conflict exists
125+
while (hasConflict(freq, conflictMap, right)) {
126+
int leftVal = left;
127+
freq.put(leftVal, freq.get(leftVal) - 1);
128+
if (freq.get(leftVal) == 0) {
129+
freq.remove(leftVal);
130+
}
131+
left++;
132+
}
133+
134+
// Number of valid subarrays ending at right
135+
valid += (right - left + 1);
136+
}
137+
138+
maxValid = Math.max(maxValid, valid);
139+
}
140+
141+
return maxValid;
142+
}
143+
144+
// Helper to check if current number conflicts with anyone in the window
145+
private boolean hasConflict(Map<Integer, Integer> freq, Map<Integer, Set<Integer>> conflictMap, int curr) {
146+
if (!conflictMap.containsKey(curr)) return false;
147+
for (int conflict : conflictMap.get(curr)) {
148+
if (freq.containsKey(conflict)) return true;
149+
}
150+
return false;
151+
}
152+
}
153+
154+
100155

101156
#### C++
102157

0 commit comments

Comments
 (0)