Untitled

 avatar
unknown
plain_text
25 days ago
638 B
1
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
    }
}
Leave a Comment