Google/fb/paypal

 Find subarray with given sum | Set 1 (Nonnegative Numbers)

  • Difficulty Level : Medium
  • Last Updated : 29 May, 2021

Given an unsorted array of nonnegative integers, find a continuous 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
Sum of elements between indices
2 and 4 is 20 + 3 + 10 = 33

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

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

There may be more than one subarrays with sum as the given sum. The following solutions print first such subarray. 



SOLUTION:

#include <iostream>

#include <bits/stdc++.h>

#include <climits>


using namespace std;




void display(int *arr, int n){


    for(int i=0;i<n;i++){


        cout<<arr[i];


    }


}






int main() {

    int arr[]={1,2,3,8};

    int n=sizeof(arr)/sizeof(int);

    int target=5;

    int i=0;

    int j=1;

    int count=0;

    int sum=0;

    while(i<n){

        while(j<n){

            sum=0;

            for(int k=i;k<=j;k++){

                sum=sum+arr[k];

            }

        if(sum<target){

            j++;

        }

        else if(sum>target){

            i++;

        }

        else if(sum==target){

            cout<<i+1<<" "<<j+1<<endl;

            count++;

            break;

        }

        if(count==1){

            break;

        }

        }

        if(count==1){

            //cout<<-1<<endl;

            break;

        }

        if(i==n-1){

            cout<<-1<<endl;

            break;

        }

    }

    

    

    



    return 0;


}

Comments

Popular posts from this blog

Sum of Even Numbers till N

Find the Runner-Up Score!

Print All Substrings