Skip to content

Commit

Permalink
Create Minimum Swaps to Group All 1's Together II.java
Browse files Browse the repository at this point in the history
  • Loading branch information
Ganeshmoorthii authored Aug 2, 2024
1 parent 393e5b4 commit a2190a4
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Day 57/Minimum Swaps to Group All 1's Together II.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution {
public int minSwaps(int[] nums) {
int ones = 0, x = 0, onesInWindow = 0, i = 0, n = nums.length;
for (int v: nums)
if (v == 1) ones++;
int nums2[] = new int[n * 2];
for (i = 0; i < n * 2; i++)
nums2[i] = nums[i % n];
for (i = 0; i < n * 2; i++) {
if (i >= ones && nums2[i - ones] == 1) x--;
if (nums2[i] == 1) x++;
onesInWindow = Math.max(x, onesInWindow);
}
return ones - onesInWindow;
}
}

0 comments on commit a2190a4

Please sign in to comment.