We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here If you see n :
1<= n <= 10 ^ 5
So it is not right way to call getSum method everytime for given array which has lenght of 10 ^ 5.
Try not to call getSum method many times as it is too expensive.
Seel my code below if it can help you out:
import java.io.;
import java.util.;
public class Solution {
int n;
int[] nums;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t =sc.nextInt();
Solution[] s = new Solution[t];
for(int i = 0 ; i < t ; i++ )
{
s[i] = new Solution();
s[i].n = sc.nextInt();
s[i].nums = new int[s[i].n];
for(int j =0 ; j < s[i].n ;j++)
{
s[i].nums[j] = sc.nextInt();
}
boolean match = false;
int totalSum = getSum(0, s[i].n - 1, s[i].nums);
int previousSum = 0, leftSum =0, rightSum = 0;
for( int k = 0 ; k < s[i].n ; k++ )
{
previousSum = previousSum + s[i].nums[k];
leftSum = previousSum - s[i].nums[k];
rightSum = totalSum - leftSum - s[i].nums[k];
if(leftSum == rightSum)
{
match = true;
break;
}
}
if(match)
System.out.println("YES");
else
System.out.println("NO");
}
}
public static int getSum(int startIndex, int endIndex, int[] arr)
{
int sum =0;
for(int i = startIndex; i<= endIndex; i++)
sum = sum + arr[i];
return sum;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Array
You are viewing a single comment's thread. Return to all comments →
Here If you see n : 1<= n <= 10 ^ 5 So it is not right way to call getSum method everytime for given array which has lenght of 10 ^ 5. Try not to call getSum method many times as it is too expensive. Seel my code below if it can help you out: import java.io.; import java.util.;
public class Solution { int n; int[] nums;
}