Tag Archives: 前缀和

LeetCode Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

Given an array nums and an integer target.

Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.

Example 1:

Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).

Example 2:

Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.

Example 3:

Input: nums = [-2,6,6,3,5,4,1,2,8], target = 10
Output: 3

Example 4:

Input: nums = [0,0,0], target = 0
Output: 3

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 0 <= target <= 10^6

给定一个数组,问数组中最多有多少个不overlap的子数组,它们的和等于target。

常规DP方法,假设dp[i]表示[0,…,i]能找到的最多的子串数目,则对于nums[i+1],如果从i+1往前,求累加和,如果累加到j的地方,累加和[j,…,i]等于target,则dp[i+1]=dp[j-1]+1。

这种思路的代码如下,需要注意for循环需要满足dp[j]==dp[i],如果dp[j]<dp[i],说明j已经回退到上一个累加和等于target的区间,已经有overlap了,需要终止。

class Solution {
public:
    int maxNonOverlapping(vector<int>& nums, int target) {
        int n = nums.size();
        vector<int> dp(n + 1, 0);
        for(int i = 1; i <= n; ++i) {
            dp[i] = dp[i - 1];
            int sum = 0;
            for(int j = i; j > 0 && dp[j] == dp[i]; --j) {
                sum += nums[j - 1];
                if(sum == target) dp[i] = max(dp[i], dp[j - 1] + 1);
            }
        }
        return dp[n];
    }
};

上述代码的时间复杂度为O(n^2),在最后几个大数据集上TLE。

参考评论区,用一个hash记录某个前缀和出现的最新下标,对于任意一个数nums[i],看看prefix_sum-target是否在之前记录的前缀和中(查hash即可),如果在,假设对应下标为j,则说明[j,…,i]之间的累加和等于target,找到一个。不过为了保证不overlap,需要保证下标j不能回退到上一个合法的累加和区间内,每次找到一个合法区间后,用right_most记录其右边界,下次只需要用j和right_most比较大小即可。

完整代码如下:

class Solution {
public:
    int maxNonOverlapping(vector<int>& nums, int target) {
        int n = nums.size();
        unordered_map<int, int> hash;
        hash[0] = -1;
        int prefix_sum = 0, right_most = -1;
        int ans = 0;
        for(int i = 0; i < n; ++i) {
            prefix_sum += nums[i];
            int supplement = prefix_sum - target;
            if(hash.find(supplement) != hash.end()) {
                int left = hash[supplement];
                if(left >= right_most) {
                    ++ans;
                    right_most = i;
                }
            }
            hash[prefix_sum] = i;
        }
        return ans;
    }
};

本代码提交AC,用时392MS。

Leetcode Running Sum of 1d Array

5453. Running Sum of 1d Array

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]

Constraints:

  • 1 <= nums.length <= 1000
  • -10^6 <= nums[i] <= 10^6

给定一个数组,求出数组的前缀和。简单题,代码如下:

class Solution {
public:
	vector<int> runningSum(vector<int>& nums) {
		int n = nums.size();
		vector<int> ans(n, 0);
		ans[0] = nums[0];
		for (int i = 1; i < n; ++i)ans[i] = ans[i - 1] + nums[i];
		return ans;
	}
};

本代码提交AC,用时12MS。

LeetCode Maximum Score After Splitting a String

1422. Maximum Score After Splitting a String

Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

Example 1:

Input: s = "011101"
Output: 5 
Explanation: 
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5 
left = "01" and right = "1101", score = 1 + 3 = 4 
left = "011" and right = "101", score = 1 + 2 = 3 
left = "0111" and right = "01", score = 1 + 1 = 2 
left = "01110" and right = "1", score = 2 + 1 = 3

Example 2:

Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5

Example 3:

Input: s = "1111"
Output: 3

Constraints:

  • 2 <= s.length <= 500
  • The string s consists of characters ‘0’ and ‘1’ only.

给定一个仅包含0/1的字符串,要求把它分成两半,使得左边的0的数目加上右边的1的数目的和最大。

简单题,提前算好左边的0的数目的累加和,和右边的1的数目的累加和。完整代码如下:

class Solution {
public:
	int maxScore(string s) {
		int n = s.size();
		vector<int> zeros(n, 0), ones(n, 0);
		for (int i = 0; i < n - 1; ++i) {
			if (i == 0)zeros[i] = (s[i] == '0' ? 1 : 0);
			else zeros[i] = zeros[i - 1] + (s[i] == '0' ? 1 : 0);

			int j = n - i - 1;
			if (j == n - 1)ones[j] = (s[j] == '1' ? 1 : 0);
			else ones[j] = ones[j + 1] + (s[j] == '1' ? 1 : 0);
		}
		int ans = 0;
		for (int i = 0; i < n - 1; ++i) {
			ans = max(ans, zeros[i] + ones[i + 1]);
		}
		return ans;
	}
};

本代码提交AC,用时4MS。