Algorithm: Find smallest subset containing K 0's

Posted by Vishal on Stack Overflow See other posts from Stack Overflow or by Vishal
Published on 2012-12-06T10:26:47Z Indexed on 2012/12/06 11:05 UTC
Read the original article Hit count: 169

Filed under:
|
|

I have array of 1's and 0's only. Now I want to find contiguous subset/subarray which contains at least K 0's.

Example Array is 1 1 0 1 1 0 1 1 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0 1 0 0 0 and K(6) should be 0 0 1 0 1 1 0 0 0 or 0 0 0 0 1 0 1 1 0....

My Solution

     Array: 1 1 0 1 1 0 1 1 0  0  0  0  1  0  1  1  0  0  0   1  1  0  0
     Index: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  20 21 22 23
     Sum:   1 2 2 3 4 4 5 6 6  6  6  6  7  7  8  9  9  9  9  10 11 11 11
Diff(I-S):  0 0 1 1 1 2 2 2 3  4  5  6  6  7  7  7  8  9 10  10 10 11 12

For K(6)

Start with 9-15 = Store difference in diff.

Next increase difference 8-15(Difference in index) 8-14(Compare Difference in index)

So on keep moving to find element with least elements...

I am looking for better algorithm for this solution.

© Stack Overflow or respective owner

Related posts about arrays

Related posts about algorithm