<p>You are given an integer array, <code>nums</code>, and an integer <code>k</code>. <code>nums</code> comprises of only <code>0</code>&#39;s and <code>1</code>&#39;s. In one move, you can choose two <strong>adjacent</strong> indices and swap their values.</p>

<p>Return <em>the <strong>minimum</strong> number of moves required so that </em><code>nums</code><em> has </em><code>k</code><em> <strong>consecutive</strong> </em><code>1</code><em>&#39;s</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,0,0,1,0,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> In 1 move, nums could be [1,0,0,0,<u>1</u>,<u>1</u>] and have 2 consecutive 1&#39;s.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,0,0,0,0,0,1,1], k = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,<u>1</u>,<u>1</u>,<u>1</u>].
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,0,1], k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> nums already has 2 consecutive 1&#39;s.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums[i]</code> is <code>0</code> or <code>1</code>.</li>
	<li><code>1 &lt;= k &lt;= sum(nums)</code></li>
</ul>

from itertools import accumulate
from typing import List

class Solution:
    def minMoves(self, nums: List[int], k: int) -> int:
        # Step 1: Extract the positions of 1's in the nums array
        one_position = [i for i, num in enumerate(nums) if num == 1]
        
        # Calculate relative positions by subtracting the index values
        # relative to their index in the list (re-centering)
        relative_position = [one_position[i] - i for i in range(len(one_position))]
        print(relative_position)
        # Step 2: Compute the prefix sum of the relative positions
        prefix_sum = list(accumulate(relative_position, initial=0))
        
        # Step 3: Initialize the minimum number of swaps to infinity
        min_swaps = float("inf")
        
        # Step 4: Iterate through each possible window of size k
        for i in range(len(relative_position) - k + 1):
            # Find the median index (middle of the window)
            mid = i + k // 2
            
            # Calculate the cost for moving elements to the median
            left_cost = relative_position[mid] * (mid - i) - (prefix_sum[mid] - prefix_sum[i])
            right_cost = (prefix_sum[i + k] - prefix_sum[mid + 1]) - relative_position[mid] * (i + k - mid - 1)
            
            # Update the minimum number of swaps
            min_swaps = min(min_swaps, left_cost + right_cost)
        
        # Step 5: Return the minimum number of swaps
        return min_swaps

27900