- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have one binary array nums, and a value k. In one move, we can select two adjacent indices and swap their values. We have to find the minimum number of moves required so that nums has k consecutive 1's.

So, if the input is like nums = [1,0,0,1,0,1,0,1], k = 3, then the output will be 2 because in one swap we can make array from [1,0,0,1,0,1,0,1] to [1,0,0,0,1,1,0,1], then [1,0,0,0,1,1,1,0].

To solve this, we will follow these steps −

j := 0

val := 0

ans := 999999

loc := a new list

for each index i, and value x in nums, do

if x is non-zero, then

insert i at the end of loc

m := quotient of (j + size of loc - 1) /2

val := val + loc[-1] - loc[m] - quotient of (size of loc -j)/2

if length of loc - j > k, then

m := quotient of (j + size of loc) /2

val := val - loc[m] - loc[j] - quotient of (size of loc -j)/2

j := j + 1

if size of loc -j is same as k, then

ans := minimum of ans and val

return ans

Let us see the following implementation to get better understanding

def solve(nums, k): j = val = 0 ans = 999999 loc = [] for i, x in enumerate(nums): if x: loc.append(i) m = (j + len(loc) - 1)//2 val += loc[-1] - loc[m] - (len(loc)-j)//2 if len(loc) - j > k: m = (j + len(loc))//2 val -= loc[m] - loc[j] - (len(loc)-j)//2 j += 1 if len(loc)-j == k: ans = min(ans, val) return ans nums = [1,0,0,1,0,1,0,1] k = 3 print(solve(nums, k))

[1,0,0,1,0,1,0,1], 3

2

- Related Questions & Answers
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python
- Program to find minimum swaps required to make given anagram in python
- Program to find minimum swaps to arrange a binary grid using Python
- Program to find minimum swaps needed to group all 1s together in Python
- Program to find minimum space plane required for skydivers in k days in python
- Program to find minimum possible difference of indices of adjacent elements in Python
- Program to find string after deleting k consecutive duplicate characters in python
- Program to find minimum cost to hire k workers in Python
- Program to find minimum amplitude after deleting K elements in Python
- Program to find maximum difference of adjacent values after deleting k numbers in python
- Max Consecutive Ones III in C++
- Max Consecutive Ones II in C++
- Program to find minimum possible maximum value after k operations in python
- Minimum Number of K Consecutive Bit Flips in C++

Advertisements