Given an array of size n, for each k from 1 to n, find the maximum sum of contiguous subarray of size k.
This problem has an obvious solution with time complexity O(N2) and O(1) space. Lua code:
array = {7, 1, 3, 1, 4, 5, 1, 3, 6}
n = #array
function maxArray(k)
ksum = 0
for i = 1, k do
ksum = ksum + array[i]
end
max_ksum = ksum
for i = k + 1, n do
add_index = i
sub_index = i - k
ksum = ksum + array[add_index] - array[sub_index]
max_ksum = math.max(ksum, max_ksum)
end
return max_ksum
end
for k = 1, n do
print(k, maxArray(k))
end
Is there any algorithm with lower time complexity? For example, O(N log N) + additional memory.
Related topics:
below process might help you
1) Pick first k elements and create a Self-Balancing Binary Search Tree (BST) of size k.
2) Run a loop for i = 0 to n – k
…..a) Get the maximum element from the BST, and print it.
…..b) Search for arr[i] in the BST and delete it from the BST.
…..c) Insert arr[i+k] into the BST.
Time Complexity: Time Complexity of step 1 is O(kLogk). Time Complexity of steps 2(a), 2(b) and 2(c) is O(Logk). Since steps 2(a), 2(b) and 2(c) are in a loop that runs n-k+1 times, time complexity of the complete algorithm is O(kLogk + (n-k+1)*Logk) which can also be written as O(nLogk).