Suppose that it can only have positive values.
Then it's easy.
The solution is one of the minimal (shortest) adjacent subarrays whose sum > K
Take two indexes, one for the beginning of the subarray and one for the end (one after the end), start with end = 0 and start = 0 . Initialization sum = 0; and min = infinity
while(end < arrayLength) { while(end < arrayLength && sum <= K) { sum += array[end]; ++end; }
As both indices only increase, the O(n) algorithm.
source share