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\lg k)$; is there a way to improve this to $O(n)$? Note that Kadane's algorithm runs in $O(n)$ time when $k=n$.