Given two arrays A and B of equal size. The task is to print any permutation of array A such that the number of indices i for which A[i] > B[i] is maximized.
Input: A = [12, 24, 8, 32], B = [13, 25, 32, 11] Output: 24 32 8 12 Input: A = [2, 7, 11, 15], B = [1, 10, 4, 11] Output: 2 11 7 15
If the smallest element in A beats the smallest element in B, we should pair them. Otherwise, it is useless for our score, as it can’t beat any other element of B.
With above strategy we make two vector of pairs, Ap for A and Bp for B with their element and respective index. Then sort both vectors and simulate them. Whenever we found any element in vector Ap such that Ap[i].first > Bp[j].first for some (i, j) we pair them i:e we update our answer array to ans[Bp[j].second] = Ap[i].first. However if Ap[i].first < Bp[j].first for some (i, j) then we store them in vector remain and finally pair them with any one.
Below is the implementation of above approach:
24 32 8 12
Time Complexity: O(N*log(N)), where N is the length of array.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Delete array elements which are smaller than next or become smaller
- Count of strings in the first array which are smaller than every string in the second array
- Count number of permutation of an Array having no SubArray of size two or more from original Array
- Find permutation array from the cumulative sum array
- Find next Smaller of next Greater in an array
- Find closest smaller value for every element in array
- First strictly smaller element in a sorted array in Java
- Construct array having X subsequences with maximum difference smaller than d
- Count of smaller or equal elements in sorted array
- Minimizing array sum by subtracting larger elements from smaller ones
- Find the nearest smaller numbers on left side in an array
- Find the permutation p from the array q such that q[i] = p[i+1] - p[i]
- Count of smaller elements on right side of each element in an Array using Merge sort
- Check if an Array is a permutation of numbers from 1 to N : Set 2
- Longest permutation subsequence in a given array
- Check if an Array is a permutation of numbers from 1 to N
- Restore a permutation from the given helper array
- Lexicographically largest permutation of the array such that a[i] = a[i-1] + gcd(a[i-1], a[i-2])
- Change the array into a permutation of numbers from 1 to n
- Maximize a number considering permutations with values smaller than limit
Improved By : rituraj_jain