Popular interview question:
Given an array of positive integers and a target integer, find if there is a consecutive subarray that sums to the target.
E.g.
Array = [1,3,6,7,8,10]
Target = 16
The subarray that sums to 16 is [3,6,7]
, so it returns true.
Traverse the array from start to end. From every index start another loop from i to the end of the array to get all subarrays starting from i, and keep a variable sum to calculate the sum. For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.
Simple Approach: Run a loop for i from 0 to n – 1, where n is the size of the array. Now, we will run a nested loop for j from i to n – 1 and add the value of the element at index j to a variable currentMax. Lastly, for every subarray, we will check if the currentMax is the maximum sum of all contiguous subarrays.
Kadane's algorithm is an iterative dynamic programming algorithm in which we search for a maximum sum contiguous subarray within a one-dimensional numeric array.
This one goes linear time (C++ code).
bool Test(const int* arr, int size, int target) {
if (target < 0) return false;
int acc = 0;
int i = 0, j = 0;
while (acc != target) {
if (acc < target) {
if (j == size) break;
acc += arr[j++];
}
else {
acc -= arr[i++];
}
}
return acc == target;
}
Note that the pre-check for a negative target value is necessary to guarantee the loop invariant that i <= j
. Specifically, when i == j
, acc
will be 0
, and a positive target guarantees that the branch under if (acc < target)
is hit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With