Sherlock and Array

  • + 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';
    }