Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 36c933f

Browse files
committed
Add solution #2134
1 parent 55482a7 commit 36c933f

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,768 LeetCode solutions in JavaScript
1+
# 1,769 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1635,6 +1635,7 @@
16351635
2131|[Longest Palindrome by Concatenating Two Letter Words](./solutions/2131-longest-palindrome-by-concatenating-two-letter-words.js)|Medium|
16361636
2132|[Stamping the Grid](./solutions/2132-stamping-the-grid.js)|Hard|
16371637
2133|[Check if Every Row and Column Contains All Numbers](./solutions/2133-check-if-every-row-and-column-contains-all-numbers.js)|Easy|
1638+
2134|[Minimum Swaps to Group All 1's Together II](./solutions/2134-minimum-swaps-to-group-all-1s-together-ii.js)|Medium|
16381639
2140|[Solving Questions With Brainpower](./solutions/2140-solving-questions-with-brainpower.js)|Medium|
16391640
2145|[Count the Hidden Sequences](./solutions/2145-count-the-hidden-sequences.js)|Medium|
16401641
2154|[Keep Multiplying Found Values by Two](./solutions/2154-keep-multiplying-found-values-by-two.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 2134. Minimum Swaps to Group All 1's Together II
3+
* https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/
4+
* Difficulty: Medium
5+
*
6+
* A swap is defined as taking two distinct positions in an array and swapping the values in them.
7+
*
8+
* A circular array is defined as an array where we consider the first element and the last element
9+
* to be adjacent.
10+
*
11+
* Given a binary circular array nums, return the minimum number of swaps required to group all
12+
* 1's present in the array together at any location.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @return {number}
18+
*/
19+
var minSwaps = function(nums) {
20+
const onesCount = nums.reduce((sum, num) => sum + num, 0);
21+
const n = nums.length;
22+
let result = Infinity;
23+
let currentZeros = 0;
24+
25+
for (let i = 0; i < onesCount; i++) {
26+
if (nums[i] === 0) currentZeros++;
27+
}
28+
29+
result = currentZeros;
30+
31+
for (let i = 1; i < n; i++) {
32+
if (nums[(i - 1) % n] === 0) currentZeros--;
33+
if (nums[(i + onesCount - 1) % n] === 0) currentZeros++;
34+
result = Math.min(result, currentZeros);
35+
}
36+
37+
return result;
38+
};

0 commit comments

Comments
 (0)