Tuesday, 3 March 2015

Hackerrank Sherlock and Array Solution

Problem Statement
Русский \| 中文
Watson gives an array A1,A2...AN to Sherlock. Then he asks him to find if there exists an element in the array, such that, the sum of elements on its left is equal to the sum of elements on its right. If there are no elements to left/right, then sum is considered to be zero.
Formally, find an i, such that, A1+A2...Ai-1 = Ai+1+Ai+2...AN.

Source Code:

 #include <cmath>  
 #include <cstdio>  
 #include <vector>  
 #include <iostream>  
 #include <algorithm>  
 using namespace std;  
 int main() {  
   /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
   int t;  
   cin>>t;  
   while(t--){  
     int arr[1000000],n,flag = 0;  
     unsigned long long lsum=0,rsum = 0;  
     cin>>n;  
     for(int i=0;i<n;i++){  
       cin>>arr[i];  
       rsum += arr[i];       
     }  
     for(int i=0;i<n;i++)   
     {  
       rsum -= arr[i];  
       if(i>0){  
         lsum += arr[i-1];  
       }  
       if(lsum == rsum){  
         flag = 1;  
       }  
     }  
     if(flag == 1){  
       cout<<"YES"<<endl;  
     }else{  
       cout<<"NO"<<endl;  
     }  
   }  
   return 0;  
 }  

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

0 comments:

Post a comment