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.
- Prepare
- Data Structures
- Trees
- Array Pairs
- Discussions
Array Pairs
Array Pairs
Sort by
recency
|
106 Discussions
|
Please Login in order to post a comment
The Problem is focusing on unnecessary things
I believe that this exercise could give 100% just with 10^5, I made my solution, with a good complexity (N x logN), but due to the constant multiplier (5), it failed in 50% of cases in Java 8 , however in Java 15 it passed in 100% of cases, with the same solution, demonstrating that the problem was not logic in itself, but rather language details and micro optimization, as for example in the comments below people having to worry about something as specific as optimizing for 1, which I already find meaningless.
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
I got 100 points using pyhton 3. Some optimizations:
I feel like this solution should work, and it appears to be doing what I think it's doing, but it only passes some of the tests. I'd be interested in knowing if anybody sees what's theoretically wrong with it.
def solve (arr): # simple but slow - combining all mx = arr [0] #max (arr) res = 0 for j in range (1, len (arr)): mx = arr [j] if arr [j] > mx else mx for i in range (j): if (arr [i] * arr [j] <= mx): res += 1 return res