leetcode 930. Binary Subarrays With Sum

This remains me of some 'subarray count' type problems…..

class Solution {
    public int numSubarraysWithSum(int[] A, int S) {
        int[] ps = new int[A.length + 1];
        ps[0] = 1;
        int sum = 0;
        int ret = 0;
        for (int v: A) {
            sum += v;
            if (sum - S >= 0) {
                ret += ps[sum - S];
            }
            ps[sum] += 1;

        }
        return ret;
    }
}

猜你喜欢

转载自www.cnblogs.com/exhausttolive/p/10618452.html
今日推荐