查找大小为 k 的子数组的最大(或最小)和
给定一个整数数组和一个数字 k,找出大小为 k 的子数组的最大和。
例子:
Input : arr[] = {100, 200, 300, 400}
k = 2
Output : 700
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}
k = 4
Output : 39
We get maximum sum by adding subarray {4, 2, 10, 23}
of size 4.
Input : arr[] = {2, 3}
k = 3
Output : Invalid
There is no subarray of size 3 as size of whole
array is 2.
一个简单的解决方案是生成大小为 k 的所有子数组,计算它们的总和,最后返回所有总和的最大值。该解决方案的时间复杂度为 O(n*k)。
一个有效的解决方案基于这样一个事实,即使用大小为 k 的前一个子阵列(或窗口)的总和可以在 O(1) 时间内获得大小为 k 的子阵列(或窗口)的总和。除了大小为 k 的第一个子数组,对于其他子数组,我们通过删除最后一个窗口的第一个元素并添加当前窗口的最后一个元素来计算总和。
下面是上述想法的实现。
C++
// O(n) solution for finding maximum sum of
// a subarray of size k
#include
using namespace std;
// Returns maximum sum in a subarray of size k.
int maxSum(int arr[], int n, int k)
{
// k must be greater
if (n < k)
{
cout << "Invalid";
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i
Java
// JAVA Code for Find maximum (or minimum)
// sum of a subarray of size k
import java.util.*;
class GFG {
// Returns maximum sum in a subarray of size k.
public static int maxSum(int arr[], int n, int k)
{
// k must be greater
if (n < k)
{
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i
Python3
# O(n) solution in Python3 for finding
# maximum sum of a subarray of size k
# Returns maximum sum in
# a subarray of size k.
def maxSum(arr, n, k):
# k must be greater
if (n < k):
print("Invalid")
return -1
# Compute sum of first
# window of size k
res = 0
for i in range(k):
res += arr[i]
# Compute sums of remaining windows by
# removing first element of previous
# window and adding last element of
# current window.
curr_sum = res
for i in range(k, n):
curr_sum += arr[i] - arr[i-k]
res = max(res, curr_sum)
return res
# Driver code
arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
k = 4
n = len(arr)
print(maxSum(arr, n, k))
# This code is contributed by Anant Agarwal.
C#
// C# Code for Find maximum (or minimum)
// sum of a subarray of size k
using System;
class GFG {
// Returns maximum sum in
// a subarray of size k.
public static int maxSum(int []arr,
int n,
int k)
{
// k must be greater
if (n < k)
{
Console.Write("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i = 0; i < k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i = k; i < n; i++)
{
curr_sum += arr[i] - arr[i - k];
res = Math.Max(res, curr_sum);
}
return res;
}
// Driver Code
public static void Main()
{
int []arr = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int k = 4;
int n = arr.Length;
Console.Write(maxSum(arr, n, k));
}
}
// This code is contributed by nitin mittal.
PHP
Javascript
输出:
24
时间复杂度: O(n)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。