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 } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter