Ram Leela

QUESTION

Ram wants to propose his girlfriend Sita but he is very nervous.Being so nervous he came with a plan to pick a number randomly.The number picked by the Ram is sum of subarrays of the main array.So help Ram to find continous subarray which adds to a given number.\n\nInput:\nThe first line of the input contains size of the array.\nThe second line consists elements of the array.\nThe third line contain the sum value to be searched.\n\nOutput:\nThe ouput contains index of the subarray.\nIf subarray not found print \”-1\.

“TESTCASE_1”: “6\n1 4 20 3 10 5\n33\n###—###SEPERATOR—###—\nSum found between indexes 2 and 4”, “TESTCASE_2”: “7\n1 4 0 0 3 10 5\n7\n###—###SEPERATOR—###—\nSum found between indexes 1 and 4”, “TESTCASE_3”: “4\n1 4 0 0\n6\n###—###SEPERATOR—###—\n-1”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;
int main()
{
  int n, i, sum, j, t;
  cin>>n;
  int a[n];
  for(i=0;i<n;i++)
    cin>>a[i];
  cin>>t;
  for(i=0;i<n;i++)
  {
    sum=0;
    for(j=i;j<n;j++)
    {
      sum+=a[j];
      if(sum==t)
      {
        cout<<"Sum found between indexes "<<i<<" and "<<j;
        return 0;
      }
      if(sum>t)
      	break;
    }
  }
  printf("-1");

	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.