I asked this over at CS.SE, but got no response.
I was recently faced with the following interview question:
Given an array A, and an integer k, find a contiguous subarray with a maximal sum, with the added constraint this subarray has length at most k.
So, if A=[8, -1, -1, 4, -2, -3, 5, 6, -3]
then we get the following answers for different values of k
:
+---+------------------------------+
| k | subarray |
+---+------------------------------+
| 1 | [8] |
| 7 | [5,6] |
| 8 | [8, -1, -1, 4, -2, -3, 5, 6] |
+---+------------------------------+
If n
is the length of the array A
, then using a modified priority queue, I was able to answer this question in time O(n lgk)
; is there a way to improve this to O(n)
? Note that Kadane's algorithm runs in O(n)
time when k=n.
5
, the max array ending there is[8, -1, -1, 4, -2, -3, 5]
. However, when you move to the6
, you need to drop the8
; that causes a chain reaction to drop the-1, -1, 4, -2, -3
, because the largest subarray of length at most 7, ending at6
, is[5,6]
. In other words, you need to keep track of which elements to "drop" as you walk the array, and a naive implementation leads to time proportional to n*k. – Steve D