📜  大小为K且和小于X的最大和子数组

📅  最后修改于: 2021-05-13 23:08:02             🧑  作者: Mango

给定一个数组ARR []和两个整数KX,任务是找到总和小于X尺寸k的所有子阵列中的最大总和。

例子:

天真的方法:解决问题的最简单方法是生成所有大小为K的子数组,并检查其总和是否小于X。打印所有此类子数组中获得的最大和。

时间复杂度: O(N * K)
辅助空间: O(1)

高效方法:按照以下步骤使用滑动窗口技术解决问题:

  1. 初始化变量sum_K来存储前K个数组元素的总和。
  2. 如果sum_K小于X,然后用sum_K初始化Max_Sum。
  3. 从第(K + 1)索引遍历数组,然后执行以下操作:
    1. 在每次迭代中,减去前K个长度子数组的第一个元素,然后将当前元素添加到sum_K
    2. 如果sum_K小于X ,则将sum_KMax_Sum进行比较,并相应地更新Max_Sum
  4. 最后,打印Max_Sum

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to calculate maximum sum
// among all subarrays of size K
// with the sum less than X
void maxSumSubarr(int A[], int N,
                  int K, int X)
{
 
    // Initialize sum_K to 0
    int sum_K = 0;
 
    // Calculate sum of first K elements
    for (int i = 0; i < K; i++) {
 
        sum_K += A[i];
    }
 
    int Max_Sum = 0;
 
    // If sum_K is less than X
    if (sum_K < X) {
 
        // Initialize MaxSum with sum_K
        Max_Sum = sum_K;
    }
 
    // Iterate over the array from
    // (K + 1)-th index
    for (int i = K; i < N; i++) {
 
        // Subtract the first element
        // from the previous K elements
        // and add the next element
        sum_K -= (A[i - K] - A[i]);
 
        // If sum_K is less than X
        if (sum_K < X) {
 
            // Update the Max_Sum
            Max_Sum = max(Max_Sum, sum_K);
        }
    }
 
    cout << Max_Sum << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { -5, 8, 7, 2, 10,
                  1, 20, -4, 6, 9 };
    int K = 5;
    int X = 30;
 
    // Size of Array
    int N = sizeof(arr)
            / sizeof(arr[0]);
 
    // Function Call
    maxSumSubarr(arr, N, K, X);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to calculate maximum sum
// among all subarrays of size K
// with the sum less than X
private static void maxSumSubarr(int A[], int N,
                                 int K, int X)
{
     
    // Initialize sum_K to 0
    int sum_K = 0;
     
    // Calculate sum of first K elements
    for(int i = 0; i < K; i++)
    {
        sum_K += A[i];
    }
     
    int Max_Sum = 0;
     
    // If sum_K is less than X
    if (sum_K < X)
    {
         
        // Initialize MaxSum with sum_K
        Max_Sum = sum_K;
    }
     
    // Iterate over the array from
    // (K + 1)-th index
    for(int i = K; i < N; i++)
    {
         
        // Subtract the first element
        // from the previous K elements
        // and add the next element
        sum_K -= (A[i - K] - A[i]);
         
        // If sum_K is less than X
        if (sum_K < X)
        {
             
            // Update the Max_Sum
            Max_Sum = Math.max(Max_Sum, sum_K);
        }
    }
     
    System.out.println(Max_Sum);
}
  
// Driver Code
public static void main (String[] args)
{
    int arr[] = { -5, 8, 7, 2, 10,
                  1, 20, -4, 6, 9 };
    int K = 5;
    int X = 30;
     
    // Size of Array
    int N = arr.length;
     
    // Function Call
    maxSumSubarr(arr, N, K, X);
}
}
 
// This code is contributed by jithin


Python3
# Python3 program for the above approach
  
# Function to calculate maximum sum
# among all subarrays of size K
# with the sum less than X
def maxSumSubarr(A, N, K, X):
     
    # Initialize sum_K to 0
    sum_K = 0
  
    # Calculate sum of first K elements
    for i in range(0, K):
        sum_K += A[i]
     
    Max_Sum = 0
  
    # If sum_K is less than X
    if (sum_K < X):
  
        # Initialize MaxSum with sum_K
        Max_Sum = sum_K
     
    # Iterate over the array from
    # (K + 1)-th index
    for i in range(K, N):
  
        # Subtract the first element
        # from the previous K elements
        # and add the next element
        sum_K -= (A[i - K] - A[i])
  
        # If sum_K is less than X
        if (sum_K < X):
             
            # Update the Max_Sum
            Max_Sum = max(Max_Sum, sum_K)
         
    print(Max_Sum)
 
# Driver Code
arr = [ -5, 8, 7, 2, 10,
         1, 20, -4, 6, 9 ]
K = 5
X = 30
  
# Size of Array
N = len(arr)
  
# Function Call
maxSumSubarr(arr, N, K, X)
 
# This code is contributed by sanjoy_62


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to calculate maximum sum
// among all subarrays of size K
// with the sum less than X
private static void maxSumSubarr(int []A, int N,
                                 int K, int X)
{
     
    // Initialize sum_K to 0
    int sum_K = 0;
     
    // Calculate sum of first K elements
    for(int i = 0; i < K; i++)
    {
        sum_K += A[i];
    }
     
    int Max_Sum = 0;
     
    // If sum_K is less than X
    if (sum_K < X)
    {
         
        // Initialize MaxSum with sum_K
        Max_Sum = sum_K;
    }
     
    // Iterate over the array from
    // (K + 1)-th index
    for(int i = K; i < N; i++)
    {
         
        // Subtract the first element
        // from the previous K elements
        // and add the next element
        sum_K -= (A[i - K] - A[i]);
         
        // If sum_K is less than X
        if (sum_K < X)
        {
             
            // Update the Max_Sum
            Max_Sum = Math.Max(Max_Sum, sum_K);
        }
    }
    Console.WriteLine(Max_Sum);
}
  
// Driver Code
public static void Main(String[] args)
{
    int []arr = { -5, 8, 7, 2, 10,
                   1, 20, -4, 6, 9 };
    int K = 5;
    int X = 30;
     
    // Size of Array
    int N = arr.Length;
     
    // Function Call
    maxSumSubarr(arr, N, K, X);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
29

时间复杂度: O(N)
辅助空间: O(1)