Hello guys, I'm having trouble with a problem.
Given an array A and a number k, find the k-th largest continuous subsequence! I can only think of a brute-force solution using prefix sum, which run in O(n ^ 2)
. In this problem n could be as large as 1e5
. Can anyone give me a hint?
Thanks in advance!
Binary search for the answer. Let the answer be x, you can find in $$$O(nlog(n))$$$ time how many elements are greater than or less than that sum using prefix sum. Total complexity $$$O(n*log(n)*log(sum))$$$.
Bin search th answer and uisng segtree and prefix sum to check i guest =))
As kindly pointer out by Farhan132, the approach below is terribly wrong. Maybe it could be useful as an exercise to find mistakes in others' solutions :D
If it is just positive numbers, there is a faster option -- two-pointers technique while keeping a multiset of $$$k$$$ largest sums so far. When extending or shrinking the window: if the multiset is less than $$$k$$$, just add the current window sum, otherwise check if it falls between the maximum and minimum value of the multiset, and if it is -- just add it to the multiset and remove the minimum from it. This will be $$$O(nlog(k))$$$, so it wouldn't depend on the overall sum — plus could be faster if $$$k$$$ is small.
Can you explain your sliding-window method? What constant subarray size are you taking?
Ah, sorry, I meant two pointers, not sliding window.