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_t5vna9N-EIMnTxsAQfKl3L0lWd0DILl58YKpuCJkMSJVgJxO1Ah9-ygJzRLdJ8wZqNFb3ZweJ3D7v0x58pbU68du1yk5qx5LQlXZFAWWYITfL2TvZHhdOPWqltHFcSWOc5JAnzeymz_ZzNFlO2JzfIt7FnuP_mb3cz1VRhXNF11Y8xsQ=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_v61qP6XRrHO1WiywzB8t1tDa2p2ut0Qtij97qXDconHYfh5IfyPNjJdYycKg4kGjGArp6_-92kHOrFvMzXf_y2jpLwc-oQ_2LY_3qApZhuljjsGmFxSLIazlLAsWfE53PLCPet8C_6N2bgrY38I4v5ztmqmgR2RLYxWw=s0-d)
![M \leftarrow M \cup \{(S[i], i)\} M \leftarrow M \cup \{(S[i], i)\}](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_uRrg4N4Qxm2vwDQSSUfo08rQR2GypWoYr0VojmPV7G6K3Q4YE6hguLPjKjdWzf3T6HBZGmC621XmOrLi06E22lsKko0qMB6XEcHj0h3OBthgk57YLYKaE3u-e2Ng7j5L83Lh9QUrw_55TZ7CxuMVpjmLDc_wo43tm3268dV74bKksPVud9TbO-o0o=s0-d)
![{\rm smallest} \leftarrow S[i] {\rm smallest} \leftarrow S[i]](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_udwTsfQL7Qg1ke0DLn3VUsP37R506_AgesXvM5l2EGAxBJQKN1FDq-Zg_-2gfdwWRwrJ29kE-Vo-A7_7DWZ26aa9x6Eq5xmc-6GOk06nTXKU6IEKi5z5yih-zEemGOMv_w8MByLkQvJU8PAvlNyod5x4MhlUiWW0GcnLnA1KB5VKOO=s0-d)
6.
7. for
up to 
if![S[i] > {\rm current} S[i] > {\rm current}](https://lh3.googleusercontent.com/blogger_img_proxy/AEn0k_spWZSCp90mxNQf9RHHkhW3dApr4eRKRsvYHRYPZXnxPJXuese_oAf9HQMtgK1kI9de1ereEizWcaDh6GetiFU1E5s3gW9grsba3hVvhVF4YM76Bgj3s08Ri0qMgvtul_rSdtOQg7Fq8_uriQyZBW1WZf2FXtpCaaPQ=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_u8Jy89xlrl7W4DtIuBIoqkOnnqCXqVHIdx3Ilv4H0Tbdbf5JOM_g414wAGqTqUXbZMBI3AJ0iomC7otemkf11iw8mLKTJqMHNt0If25xTnkazQbC_z3n3OtZhaiGb7A7ePkeGu7hpMlYSTxhBT3u2q_MjxjssDcQeSDDL_vkXIGk3Z=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