diff options
author | Jack Sangdahl <[email protected]> | 2024-08-01 21:42:36 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-08-01 21:42:36 -0600 |
commit | 3dd518795de5a8372b39a6f6984acb0b2d5d5dbc (patch) | |
tree | e65d2d78171c0061e7e4f35a99f12b0c19534ad6 | |
parent | 801d7b66811d0c554c1a9cfa174610807c97609f (diff) | |
download | leetcode-3dd518795de5a8372b39a6f6984acb0b2d5d5dbc.tar.gz leetcode-3dd518795de5a8372b39a6f6984acb0b2d5d5dbc.zip |
2134. minimum swaps to group all 1's together
-rw-r--r-- | min_swap_group_1.c | 3 | ||||
-rw-r--r-- | min_swap_group_1.py | 33 |
2 files changed, 34 insertions, 2 deletions
diff --git a/min_swap_group_1.c b/min_swap_group_1.c index 4fa2384..2536259 100644 --- a/min_swap_group_1.c +++ b/min_swap_group_1.c @@ -1,6 +1,5 @@ // 2134. Minimum Swaps to Group All 1's Together II -#include <math.h> -#include <stdio.h> +#include "leetcode.h" #pragma GCC optimize("-O3") /* diff --git a/min_swap_group_1.py b/min_swap_group_1.py new file mode 100644 index 0000000..4365fa8 --- /dev/null +++ b/min_swap_group_1.py @@ -0,0 +1,33 @@ +# 2134. Minimum Swaps to Group All 1's Together II + +""" +a swap is defined as taking two distinct position in an array and swapping +the values in them. a circular array is defined as an array where we consider +the first element and the last element to adjacent. given a binary circular +array 'nums', return the minimum number of swaps required to group all 1's +preent in the array together at any location. +""" + + +class Solution(object): + def minSwaps(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + ones, nums = nums.count(1), nums + nums + x, curr_ones = 0, 0 + for i in range(len(nums)): + if i >= ones and nums[i - ones]: + x -= 1 + if nums[i] == 1: + x += 1 + curr_ones = max(x, curr_ones) + return ones - curr_ones + + +if __name__ == "__main__": + obj = Solution() + print(obj.minSwaps(nums=[0, 1, 0, 1, 1, 0, 0])) + print(obj.minSwaps(nums=[0, 1, 1, 1, 0, 0, 1, 1, 0])) + print(obj.minSwaps(nums=[1, 1, 0, 0, 1])) |