Friday, 1 June 2012

Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.


Examples:
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Ouptut: Sum found between indexes 1 and 4

Input: arr[] = {1, 4}, sum = 0
Output: No subarray found


Solution:

Since all numbers are positive so the sum, we can do this without needing a DP array/table.

Maintain a running sum, which adds all elements from start_pos to curr_pos, until the sum becomes greater than the given number. When sum > given number remove the starting elements until the sum becomes <= the given number.

http://www.geeksforgeeks.org/archives/19267

No comments:

Post a Comment