Q62 Tricky Sorting Cost | Practice | GeeksforGeeks

PHOTO EMBED

Sat Feb 04 2023 06:43:13 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution{
    static int sortingCost(int N, int arr[]){
        
        //make a HM to store consequtive subsequence
        HashMap<Integer,Integer> map = new HashMap<>();
        
        int max_subs = 0 ;
        
        for (int i =0 ; i < N ; i++){
            
            int val = arr[i];
            
            //if substring continues update length against new value
            if(map.containsKey(val-1))
            map.put(val , map.get(val-1)+1);
            
            else
            map.put(val , 1);
            
            max_subs = Math.max(max_subs,map.get(val));     //store maximum substring
        }
        
        return N-max_subs;      //return total - longest substring as minimum no. of operations
    }
}
content_copyCOPY

https://practice.geeksforgeeks.org/problems/morning-assembly3038/0