We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
count 1 in the array but do not append to your array from the input
Solution for one
1*k <= max(k, x)
For 1st 1 in the array, there are n-1 pairs
For 2nd 1, there are more n-2 pairs
For 3rd 1, there are more n-3 pairs
...
For last 1, supposing there are k 1 in the array, there are more n-k pairs
ans_for_ones = n-1 + n-2 + n-3 + ... + n-k
= n*k - k*(k+1)/2
we will do divide and conquer algorithm and modify merge sort like this
find max element
find first index of the max element
if the max element is side by side consecutively, find its last index too
# in merge_sort methodmx=max(arr[l:r+1])midleft=lforiinrange(l,r+1):ifarr[i]==midleft:midleft=ibreakmidright=midleftwhilemidright+1<=randarr[midright+1]==mx:midright+=1merge_sort(l,midleft-1)merge_sort(midright+1,r)
(sorted left_side) (max elements) (sorted right_side) [after using merge sort in smaller segments of the array]
=> (merge left_side and right_side) (max elements) = (sorted array)
Array Pairs
You are viewing a single comment's thread. Return to all comments →
count 1 in the array but do not append to your array from the input
Solution for one
1*k <= max(k, x)
For 1st 1 in the array, there are n-1 pairs
For 2nd 1, there are more n-2 pairs
For 3rd 1, there are more n-3 pairs
...
For last 1, supposing there are k 1 in the array, there are more n-k pairs
ans_for_ones = n-1 + n-2 + n-3 + ... + n-k
= n*k - k*(k+1)/2
we will do divide and conquer algorithm and modify merge sort like this
(sorted left_side) (max elements) (sorted right_side) [after using merge sort in smaller segments of the array]
=> (merge left_side and right_side) (max elements) = (sorted array)
For example:
4 1 3 5 1 12 12 12 12* 4 2 12 4 1
1 1 3 4 5 12 12 12 12* 1 2 4 4 12
after everything
ans = ans + ans_for_ones
Full code: https://github.com/SR-Hossain/Coding-Platform-Problem-Solve/blob/main/LeetCode/Array%20Pairs.md