Sherlock and Array

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