I have been given an array A of integers. Now I have to found out a sub-array(a sub-sequence of original array) where sum of every pair is greater than or equal to a pre-defined K.
What I thought :-
sorted[i] + sorted[i+1]>=ksorted[i]Repeat the above for all the elements of the array.
Running Time :- O(nlgn)
Is the solution optimal ? Can we further improve it ?
Example :-
-10 -100 5 2 4 7 10 23 81 5 25
Sorted Array
-100 -10 2 4 5 5 7 10 23 25 81
Let K = 20
Sub Array : -
10 23 25 81
Had the question been to find out longest sub-array, algorithm suggested by alestanis in the answers would work fine :)
Here is a fairly simple solution.
>>> def f(A, k):
... solution = [item for item in A if 2*item >= k]
... m = min(solution)
... for item in A:
... if item + m >= k and 2*item < k:
... solution.append(item)
... break
... return solution
...
>>> f([-10, -100, 5, 2, 4, 7, 10, 23, 81, 5, 25], 20)
[10, 23, 81, 25]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With