Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, March 1, 2021

Minimum swaps to make K together


Problem : 

Given an array of n positive integers and a number k. Find the minimum number of swaps required to bring all the numbers less than or equal to k together.


Number of Swap = number of elements <=k not connected to maxArea of connected elements <=k

So idea is count numbers less than equal to k and check for max consecutive box, subtract it from count.


Code : 

 public static int minSwap (int a[], int n, int k) {
        int consecutiveElements = 0;
        int maxSoFar = 0;
        int count = 0;
        for(int i =0 ;i<n; ++i) {
            if(a[i]<=k) {
                ++count;
                ++maxSoFar;
            }
            else
            maxSoFar = 0;
            consecutiveElements= Math.max(consecutiveElements, maxSoFar);
        }
        return count-consecutiveElements;
    }

0 Comments:

Post a Comment

Stats