Longest subarray whose sum <= k
Longest subarray whose sum
Given an array
of
numbers and a key
, find the longest subarray of
for which the subarray sum is less than or equal to
.
In the following we describe an algorithm with time complexity
.
Algorithm LONGESTSUBARRAY(
,
)
Longest_subarray_k_improved.cpp LongestSubarrayK.java
Longest subarray whose sum
Given an array
In the following we describe an algorithm with time complexity
Algorithm LONGESTSUBARRAY(
Input: An array
and a real number 
Output: A pair of indices
, maximizing
, subject to ![\sum_{t = i}^j A[t] \leq k \sum_{t = i}^j A[t] \leq k](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_v5p4UzfkMdmDtJwzIfZIplywNIOesDyDPeRr8dMFwSq8gOkgQ3RNPphNTC-8yJTEsF3LpTrPFAxp88ZZe4ovvmT1N-g2sm3FmEVpUiJM4d--tmJoIYFPOlUEJd4ZhVmhd6BMs5Khk01lSsSOvXBVyQbE8b8vcY47dfJVux31Takc6WCg=s0-d)
1. Compute the array
of partial sums, where
is the prefix sum of the first
numbers in
.
.
2.
3.
4.
5. for
down to 0
if![S[i] < {\rm smallest} S[i] < {\rm smallest}](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_vuGdfGoF4JhEp2PjuY7V4IOcLpG5f9I7fSORHj6W0oexlQ1vTXG4uaDQtpOymN_MAKewPk9YIeBAfrdHnZXeGSBdMZn0l-lzXx6Wor9oH7DkYFVvIIjI6iMu-iFnZ6aNa0V9ODKS8XzdunvNkFqSt5-qD0NilBWkJdZA=s0-d)
![M \leftarrow M \cup \{(S[i], i)\} M \leftarrow M \cup \{(S[i], i)\}](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_tqFQPso5ftEdcAnwn_3K6sgYhTxWcfbcq1f1H2KlKX_XRAmtAKjUq57_N_5WVKoThAf_IMiyDODb0EMXXq9OjiZzWP09TLGq4LAz92enIZc9qpyJX3tTPA8nbMlIQS8o32slR4sd2Cc0P9pfm8AWEjYkdiT-t3des92ZwyXoEfuWTZ0FYaTOnvm8E=s0-d)
![{\rm smallest} \leftarrow S[i] {\rm smallest} \leftarrow S[i]](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_vo_mZSlDQrHWEHi6qt15UE5nBAvc0JrwUSmeYPThuU5RGwJZEZyh8INS9uIYBruy22xRPt0hS_oSu7RucTPXROeClK_npDyb7mXbdStOzhVPk1PtSZ97xvHZtoryE3vE9hQxX_XIpcAqnrK9f10TiaFwoh5Dj4FqgjiHFTSUTDZtT8=s0-d)
6.
7. for
up to 
if![S[i] > {\rm current} S[i] > {\rm current}](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_v6lx1T5WJBrijjN77Z5ZYeZChVNG7EagZcDWOAKiDpghUNHdGKH5mr0ZfRdApZiazHDM2OTRAdDn5reXvG87Pkz9LidWBPHhQQudRZXDKYaGh8diYcF6q_ZAWthxtym0zZcWTF8rB10BSmgq96A_-ej67bw2DtYQDM=s0-d)
Use binary search to look for the rightmost element
in
such that
. If such an element exists, update
to
if 
![{\rm current} \leftarrow S[i] {\rm current} \leftarrow S[i]](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_t3I-ZneII8z9xdRuZKrl-eGjDeUevGH5GuuqfCfiN3H7GiYGnlvn0ucJXP9wmZCjl83XQBJvQUGvX04K7yLtXjflvZUnEYdt4TGJsMUmIwGSuZ53kSe_MkcFa69k8WNVTfAeOOfxRlYkKT5dU9gONTm8-GG4VF5O6A2WlkuXN3XLyg=s0-d)
8. return
Find the longest subarray whose sum <= kOutput: A pair of indices
1. Compute the array
2.
3.
4.
5. for
if
6.
7. for
if
Use binary search to look for the rightmost element
8. return
Longest_subarray_k_improved.cpp LongestSubarrayK.java
public static Pair<Integer, Integer> findLongestSubarrayLessEqualK(
List<Integer> A, int k) {
// Build the prefix sum according to A.
List<Integer> prefixSum = new ArrayList<>();
int sum = 0;
for (int a : A) {
sum += a;
prefixSum.add(sum);
}
List<Integer> minPrefixSum = new ArrayList<>(prefixSum);
for (int i = minPrefixSum.size() - 2; i >= 0; --i) {
minPrefixSum.set(i,
Math.min(minPrefixSum.get(i), minPrefixSum.get(i + 1)));
}
Pair<Integer, Integer> arrIdx = new Pair<>(0,
upperBound2(minPrefixSum, k) - 1);
for (int i = 0; i < prefixSum.size(); ++i) {
int idx = upperBound2(minPrefixSum, k + prefixSum.get(i)) - 1;
if (idx - i - 1 > arrIdx.getSecond() - arrIdx.getFirst()) {
arrIdx = new Pair<>(i + 1, idx);
}
}
return arrIdx;
}
Correctness of the Algorithm
The key is to observe the following two facts.
Claim: (1) If two indices
satisfies that
, then
cannot appear in an optimum solution; (2) If two indices
satisfies that
, then
cannot appear in an optimum solution.
Proof: For any index
,
, note that the subarray sum of
is less than the subarray sum of
, and the length of the subarray $A[i..r']$ is greater than the length of the subarray
(although both length might be negative, but the statement still holds). Therefore,
is preferable over
. This is also the reason why we compute the strictly increasing sequence of
.
The second statement follows a similar reasoning.
Claim: (1) If two indices
Proof: For any index
The second statement follows a similar reasoning.
Time Complexity and Space Complexity
Step 1, computing the prefix sums, takes
time. Step 4, computing the array
, takes
time. Step 7 takes
time as each iteration takes
time.
Please read full article from Longest subarray whose sum <= kStep 1, computing the prefix sums, takes