这类题目不需要额外的数据结构辅助
1.Maximum Sum Subarray of Size K (easy)
问题描述
给定一个正数数组和一个正数“k”,求任何大小为“k”的连续子数组的最大和。
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: 和最大的连续子数组为 [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: 和最大的连续子数组为 [3, 4].
解题的关键:
1.问题需要提交的是连续子数组的和,子数组是连续的所以我们在计算和的时候会有重复的部分,所以可以用滑动窗口来解决。窗口从前一个位置到后一个位置需要做的是先加上尾部,后减去头部,这可以和我们的窗口收缩扩张联系在一起。
2.这个题目比较简单,因为滑动窗口的大小已经给定了,就是“k”,所以我们最需要关心的窗口缩小问题已经显而易见的的得到答案了,就是在窗口大小大于k时(在本题中只有窗口尾部在k-1及以后的位置上,窗口大小才可能大于k),窗口头部向前移动(减去头部)。
3.用一个数来记录窗口在循环中的最大和即可
代码:
int findMaxSumSubArray(int k, const vector<int>& arr) {
int windowSum = 0, maxSum = 0;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.size(); windowEnd++) {
windowSum += arr[windowEnd]; // 加上尾部
if (windowEnd >= k - 1) //窗口收缩的时机是,窗口大小大于k时
{
maxSum = max(maxSum, windowSum);
windowSum -= arr[windowStart]; // 减去头部
windowStart++; // 窗口收缩
}
}
return maxSum;
}
2.Smallest Subarray With a Greater Sum (easy)
问题描述
给定一个正数数组和一个正数“S”,找出总和大于或等于“S”的最小连续子数组的长度。 如果不存在这样的子数组,则返回 0。
Example 1:
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a sum greater than or equal to '7' is [5, 2].
Example 2:
Input: [2, 1, 5, 2, 8], S=7
Output: 1
Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
Example 3:
Input: [3, 4, 1, 1, 6], S=8
Output: 3
Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
解题的关键:
1.本题求的是总和大于或等于“S”的最小连续子数组的长度,因为是最小的长度,窗口的大小是不确定的,所以在窗口大小刚满足条件时就可以收缩窗口了
2.需要一个数来记录窗口内数的和,另一个来记录最小的长度
代码:
int findMinSubArray(int S, const vector<int>& arr) {
int windowSum = 0, minLength = INT_MIN;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.size(); windowEnd++) {
windowSum += arr[windowEnd]; // 窗口扩展
while (windowSum >= S) //窗口缩小的时机是窗口内部数的和大于S,缩小一次和可能还大于S,所以使用while
{
minLength = min(minLength, windowEnd - windowStart + 1);
windowSum -= arr[windowStart];
windowStart++; //窗口缩小
}
}
return minLength > 0 ? minLength :0;//注意窗口最小值为0
}