Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to find subarray from a given sum in C++

1 Answer

0 votes
#include <bits/stdc++.h> 

using namespace std; 

void find_sub_array(int arr[], int len, int sum, int &start, int &end) { 
    unordered_map<int, int> map; 
    int current_sum = 0; 

    for (int i = 0; i < len; i++) { 
        current_sum = current_sum + arr[i]; 

        if (current_sum == sum) { 
            end = i;
            return; 
        } 

        if (map.find(current_sum - sum) != map.end()) { 
            start = map[current_sum - sum] + 1;
            end  = i;
            return; 
        } 
        map[current_sum] = i; 
    } 
} 
  
int main() 
{ 
    int arr[] = {6, 1, 4, -1, 5, -1, 2}; 
    int len = sizeof(arr)/sizeof(arr[0]); 
    int sum = 9, start = 0, end = 0;
  
    find_sub_array(arr, len, sum, start , end); 
    
    cout << "from index " << start << " to " << end << endl; 
  
    return 0; 
} 


/*
run:

from index 1 to 4

*/

 



answered Apr 7, 2019 by avibootz
edited Apr 7, 2019 by avibootz

Related questions

...