leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 3dd518795de5a8372b39a6f6984acb0b2d5d5dbc
parent 801d7b66811d0c554c1a9cfa174610807c97609f
Author: Jack Sangdahl <jack@pngu.org>
Date:   Thu,  1 Aug 2024 21:42:36 -0600

2134. minimum swaps to group all 1's together

Diffstat:
Mmin_swap_group_1.c | 3+--
Amin_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 @@ -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 @@ -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]))