Sherlock and Array

Sort by

recency

|

961 Discussions

|

  • + 0 comments

    Here is my c++ solution, you can watch the explanation here : https://youtu.be/-kwepBHt_jM

    string balancedSums(vector<int> arr) {
        int ls = 0, rs = accumulate(arr.begin(), arr.end(), 0);
        for(int i = 0; i < arr.size(); i++){
            rs -= arr[i];
            if(i != 0) ls += arr[i-1];
            if(ls == rs) return "YES";
        }
        return "NO";
    }
    
  • + 0 comments

    Here is the solution in Py3

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # 
    #Complete the 'balancedSums' function below.
    #
    # The function is expected to return a STRING.
    # The function accepts INTEGER_ARRAY arr as parameter.
    #
    for t in range(int(input())):
        n = int(input())
        a = [int(b) for b in input().split()]
        s = sum(a)
        count = 0
        for i in range(n):
            if 2*count == s-a[i]:
                print("YES")
                break
            count += a[i]
        else:
            print("NO")
    
  • + 0 comments

    C#

    public static string balancedSums(List<int> arr)
    {
        var len = arr.Count;
        var total = arr.Sum(x => (long)x);
        long leftSum = 0;
        long rightSum = total;
    
        for (int i = 0; i < len; ++i)
        {
            rightSum = rightSum - arr[i];
            var leftIndex = (i == 0) ? 0 : i - 1;
    
            if (i > 0)
            {
                leftSum = leftSum + arr[leftIndex];
            }
    
            if (leftSum == rightSum)
            {
                return "YES";
            }
        }
    
        return "NO";
    }
    
  • + 0 comments
    def balancedSums(arr):
        # Write your code here
        left = 0
        right = sum(arr)
        for i in range(len(arr)):
            if i != 0:
                left += arr[i-1]
            right -= arr[i]
            if left == right:
                return 'YES'
        return 'NO'
    
  • + 0 comments
    def balancedSums(arr):
        # Write your code here
        lsum=0
        rsum=sum(arr)
        res='NO'
        for i in range(len(arr)):
            rsum-=arr[i]
            if lsum==rsum:
                res = 'YES'
                break
            lsum+=arr[i]
        return res