Untitled
unknown
plain_text
10 months ago
638 B
3
Indexable
// accepted by LC
class Solution {
public int minSwaps(int[] arr) {
int sum = 0;
int n = arr.length;
// k = Total count of 1s
for (int i = 0; i < n; i++) {
sum += arr[i];
}
int k = sum;
int i = 0, j = 0;
sum = 0;
// Process the first k elements
while (j < k) {
sum += arr[j];
j++;
}
int maxi = sum; // Initialize maxi with the sum of the first window
// Slide the window through the array (circularly)
while (i < n - 1) {
sum += arr[j % n];
sum -= arr[i];
maxi = Math.max(maxi, sum);
j++;
i++;
}
return k - maxi; // Minimum swaps required
}
}Editor is loading...
Leave a Comment