Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a subarray that sums to a target?

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.

like image 380
Akash Magoon Avatar asked Oct 06 '15 02:10

Akash Magoon


People also ask

How do you calculate Subarray?

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.

How do you sum a maximum 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.

What is kadane algorithm?

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.


Video Answer


1 Answers

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.

like image 127
Lingxi Avatar answered Sep 23 '22 21:09

Lingxi