You are given an integer array, nums, and an integer k. nums comprises of only 0’s and 1’s. In one move, you can choose two adjacent indices and swap their values.
Return _theminimum number of moves required so that _numshask
_consecutive _1’ s.
To minimize the number of adjacent swaps needed to group k ones together, we can focus on the positions of the ones. The optimal group of k ones will be consecutive in the positions array, and the minimum swaps is the sum of distances to the median position in that group, minus the natural offsets.
classSolution {
public:int minMoves(vector<int>& nums, int k) {
vector<int> pos;
for (int i =0; i < nums.size(); ++i) if (nums[i] ==1) pos.push_back(i);
vector<longlong> pre(pos.size()+1);
for (int i =0; i < pos.size(); ++i) pre[i+1] = pre[i] + pos[i];
longlong ans = LLONG_MAX;
for (int i =0; i + k <= pos.size(); ++i) {
int mid = i + k/2;
longlong left = pre[mid] - pre[i];
longlong right = pre[i+k] - pre[mid+1];
longlong moves = right - left;
if (k %2==0) moves += pos[mid];
ans = min(ans, moves);
}
return ans;
}
};
classSolution {
publicintminMoves(int[] nums, int k) {
List<Integer> pos =new ArrayList<>();
for (int i = 0; i < nums.length; ++i) if (nums[i]== 1) pos.add(i);
long[] pre =newlong[pos.size()+1];
for (int i = 0; i < pos.size(); ++i) pre[i+1]= pre[i]+ pos.get(i);
long ans = Long.MAX_VALUE;
for (int i = 0; i + k <= pos.size(); ++i) {
int mid = i + k/2;
long left = pre[mid]- pre[i];
long right = pre[i+k]- pre[mid+1];
long moves = right - left;
if (k % 2 == 0) moves += pos.get(mid);
ans = Math.min(ans, moves);
}
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funminMoves(nums: IntArray, k: Int): Int {
val pos = nums.indices.filter { nums[it] ==1 }
val pre = LongArray(pos.size+1)
for (i in pos.indices) pre[i+1] = pre[i] + pos[i]
var ans = Long.MAX_VALUE
for (i in0..pos.size-k) {
val mid = i + k/2val left = pre[mid] - pre[i]
val right = pre[i+k] - pre[mid+1]
var moves = right - left
if (k % 2==0) moves += pos[mid]
ans = minOf(ans, moves)
}
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defmin_moves(nums: list[int], k: int) -> int:
pos = [i for i, v in enumerate(nums) if v ==1]
pre = [0]
for p in pos:
pre.append(pre[-1] + p)
ans = float('inf')
for i in range(len(pos)-k+1):
mid = i + k//2 left = pre[mid] - pre[i]
right = pre[i+k] - pre[mid+1]
moves = right - left
if k %2==0:
moves += pos[mid]
ans = min(ans, moves)
return int(ans)
impl Solution {
pubfnmin_moves(nums: Vec<i32>, k: i32) -> i32 {
let pos: Vec<usize>= nums.iter().enumerate().filter_map(|(i, &v)|if v ==1 { Some(i) } else { None }).collect();
letmut pre =vec![0; pos.len()+1];
for i in0..pos.len() {
pre[i+1] = pre[i] + pos[i];
}
letmut ans =i64::MAX;
for i in0..=pos.len()-k asusize {
let mid = i + k asusize/2;
let left = pre[mid] - pre[i];
let right = pre[i+k asusize] - pre[mid+1];
letmut moves = right asi64- left asi64;
if k %2==0 {
moves += pos[mid] asi64;
}
ans = ans.min(moves);
}
ans asi32 }
}