Sherlock and Array

Sort by

recency

|

150 Discussions

|

  • + 0 comments

    short c++ solution using prefix sums - i-th element is the sum of all the previous elements + the i-th element of arr.

    string balancedSums(vector<int> arr) {
        bool ok = false;
        
        int n = arr.size();
        vector<int> a(n+1,0);
        
        for (int i = 1; i <= n; i++) {
            a[i] = a[i-1] + arr[i-1];
        }
        
        for (int i = 1; i < n; i++) {
            int l = a[i-1];
            int r = a[n]-a[i];
            ok |= (r==l);
        }
        return ok or n==1 ? "YES" : "NO";
    }
    
  • + 0 comments
    from functools import reduce
    
    def balancedSums(arr):
        sum_arr = sum(arr)
        return 'YES' if (reduce(lambda a, b: a + (b if a <= sum_arr // 2 else 0), arr) == reduce(lambda a, b: a + (b if a <= sum_arr // 2 else 0), reversed(arr))) else 'NO'
    
  • + 0 comments

    The test case is wrong! ( 2 0 0 0 & 0 0 2 0)

    Constraints: 1 <= arr[i] <= 2 x 10^4

  • + 0 comments

    Javascript

    function balancedSums(arr: number[]): string {
      if (arr.length === 1) {
        return 'YES';
      }
      
      let balanceIdx = Math.floor(arr.length/2);
      let leftSum = arr.slice(0, balanceIdx).reduce((total, val) => total + val, 0);
      let rightSum = arr.slice(balanceIdx+1).reduce((total, val) => total + val, 0);
      
      if (leftSum === rightSum) {
        return 'YES';
      }
      
      const dir = leftSum < rightSum ? 1 : -1;
      
      while (balanceIdx !== -1 && balanceIdx !== arr.length) {
        const prevBalancePt = arr[balanceIdx];
        balanceIdx += dir;
        const newBalancePt = arr[balanceIdx];
        
        if (dir === 1) {
          leftSum += prevBalancePt;
          rightSum -= newBalancePt;
        } else {
          leftSum -= prevBalancePt;
          rightSum += newBalancePt;
        }
        
        if (leftSum === rightSum) {
         return 'YES';
        }
      }
      
      return 'NO';
    }
    
  • + 0 comments

    C# SOLUTION

    int[] intArray = arr.ToArray(); if (arr.Count() == 1){ return "YES"; } int[] startEndSums = { 0 , intArray[..].Sum() };

        for (int i = 0; i < arr.Count(); i++){
            startEndSums[1] -= intArray[i];
            if (startEndSums[0] == startEndSums[1])
                return "YES";
            startEndSums[0] += intArray[i];
        }
        return "NO";