📌  相关文章
📜  大小为K的子数组之和之间的最大绝对差

📅  最后修改于: 2021-06-27 01:00:58             🧑  作者: Mango

给定大小为N的数组arr []和整数K ,任务是找到大小为K的子数组之和之间的最大绝对差。
例子 :

天真的方法
最简单的方法是生成所有大小为K的子数组,并在其中找到最小和最大。最后,返回最大和最小和之间的绝对差。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效方法
这个想法是使用滑动窗口技术。请按照以下步骤解决问题:

  1. 检查K是否大于N,然后返回-1。
    • maxSum :存储K大小子数组的最大和。
    • minSum :存储K大小子数组的最小和。
    • sum :存储K大小子数组的当前和。
    • start :删除不再是K大小子数组一部分的最左边的元素。
  2. 计算前K大小的子阵列和更新maxSumminSum的总和,通过ARR减量总和[开始]和由1个增量的开始
  3. 遍历给K常用3N,然后执行以下操作:
    • 将总和增加arr [i]
    • 更新maxSumminSum
    • 通过arr [start]减少总和
    • 增量1开始
  4. 返回maxSumminSum之间的绝对差。

下面是上述方法的实现:

C++
// C++ program to find the
// maximum absolute difference
// between the sum of all
// subarrays of size K
#include 
using namespace std;
 
// Return absolute difference
// between sum of all subarrays
// of size k
int MaxAbsSumOfKsubArray(int arr[],
                         int K, int N)
{
     
    // Stores maximum sum of
    // all K size subarrays
    int maxSum = INT_MIN;
 
    // Stores minimum sum of
    // all K size subarray
    int minSum = INT_MAX;
 
    // Stores the sum of current
    // subarray of size K
    int sum = 0;
 
    // Starting index of the
    // current subarray
    int start = 0;
 
    int i = 0;
 
    if (N < K)
        return -1;
 
    // Calculate the sum of
    // first K elements
    while (i < K)
    {
        sum += arr[i];
        i++;
    }
 
    // Update maxSum and minSum
    maxSum = max(maxSum, sum);
    minSum = min(minSum, sum);
 
    // Decrement sum by arr[start]
    // and increment start by 1
    sum -= arr[start++];
 
    // Traverse arr for the
    // remaining subarrays
    while (i < N)
    {
 
        // Increment sum by arr[i]
        sum += arr[i];
 
        // Increment i
        i++;
 
        // Update maxSum and minSum
        maxSum = max(maxSum, sum);
        minSum = min(minSum, sum);
 
        // Decrement sum by arr[start]
        // and increment start by 1
        sum -= arr[start++];
    }
 
    // Return absolute difference
    // between maxSum and minSum
    return abs(maxSum - minSum);
}
 
// Driver code
int main()
{
    int arr[] = { -2, -3, 4, -1,
                  -2, 1, 5, -3 };
    int K = 3;
    int N = sizeof(arr) / sizeof(arr[0]);
     
    cout << MaxAbsSumOfKsubArray(arr, K, N)
         << endl;
          
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java
// Java program to find the
// maximum absolute difference
// between the sum of all
// subarrays of size K
 
import java.util.*;
 
class GFG {
 
    // Return absolute difference
    // between sum of all subarrays
    // of size k
    static int MaxAbsSumOfKsubArray(
        int[] arr,
        int K, int N)
    {
        // Stores maximum sum of
        // all K size subarrays
        int maxSum = Integer.MIN_VALUE;
 
        // Stores minimum sum of
        // all K size subarray
        int minSum = Integer.MAX_VALUE;
 
        // Stores the sum of current
        // subarray of size K
        int sum = 0;
 
        // Starting index of the
        // current subarray
        int start = 0;
 
        int i = 0;
 
        if (N < K)
            return -1;
 
        // Calculate the sum of
        // first K elements
        while (i < K) {
            sum += arr[i];
            i++;
        }
 
        // Update maxSum and minSum
        maxSum = Math.max(maxSum, sum);
        minSum = Math.min(minSum, sum);
 
        // Decrement sum by arr[start]
        // and increment start by 1
        sum -= arr[start++];
 
        // Traverse arr for the
        // remaining subarrays
        while (i < N) {
 
            // Increment sum by arr[i]
            sum += arr[i];
 
            // Increment i
            i++;
 
            // Update maxSum and minSum
            maxSum = Math.max(maxSum, sum);
            minSum = Math.min(minSum, sum);
 
            // Decrement sum by arr[start]
            // and increment start by 1
            sum -= arr[start++];
        }
 
        // Return absolute difference
        // between maxSum and minSum
        return Math.abs(maxSum - minSum);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { -2, -3, 4, -1,
                      -2, 1, 5, -3 };
        int K = 3;
        int N = arr.length;
        System.out.println(
            MaxAbsSumOfKsubArray(
                arr, K, N));
    }
}


Python3
# Python3 program to find the
# maximum absolute difference
# between the sum of all
# subarrays of size K
import sys
 
# Return absolute difference
# between sum of all subarrays
# of size k
def MaxAbsSumOfKsubArray(arr, K, N):
     
    # Stores maximum sum of
    # all K size subarrays
    maxSum = - sys.maxsize - 1
 
    # Stores minimum sum of
    # all K size subarray
    minSum = sys.maxsize
 
    # Stores the sum of current
    # subarray of size K
    sum = 0
 
    # Starting index of the
    # current subarray
    start = 0
 
    i = 0
 
    if (N < K):
        return -1
 
    # Calculate the sum of
    # first K elements
    while (i < K):
        sum += arr[i]
        i += 1
     
    # Update maxSum and minSum
    maxSum = max(maxSum, sum)
    minSum = min(minSum, sum)
 
    # Decrement sum by arr[start]
    # and increment start by 1
    sum -= arr[start]
    start += 1
 
    # Traverse arr for the
    # remaining subarrays
    while (i < N):
 
        # Increment sum by arr[i]
        sum += arr[i]
 
        # Increment i
        i += 1
 
        # Update maxSum and minSum
        maxSum = max(maxSum, sum)
        minSum = min(minSum, sum)
 
        # Decrement sum by arr[start]
        # and increment start by 1
        sum -= arr[start]
        start += 1
 
    # Return absolute difference
    # between maxSum and minSum
    return abs(maxSum - minSum)
 
# Driver code
arr = [ -2, -3, 4, -1,
        -2, 1, 5, -3 ]
K = 3
N = len(arr)
     
print(MaxAbsSumOfKsubArray(arr, K, N))
 
# This code is contributed by sanjoy_62


C#
// C# program to find the
// maximum absolute difference
// between the sum of all
// subarrays of size K
using System;
class GFG{
 
// Return absolute difference
// between sum of all subarrays
// of size k
static int MaxAbsSumOfKsubArray(
       int[] arr,
       int K, int N)
{
    // Stores maximum sum of
    // all K size subarrays
    int MaxSum = Int32.MinValue;
 
    // Stores minimum sum of
    // all K size subarray
    int MinSum = Int32.MaxValue;
 
    // Stores the sum of current
    // subarray of size K
    int sum = 0;
 
    // Starting index of the
    // current subarray
    int start = 0;
 
    int i = 0;
 
    if (N < K)
        return -1;
 
    // Calculate the sum of
    // first K elements
    while (i < K)
    {
        sum += arr[i];
        i++;
    }
 
    // Update maxSum and minSum
    MaxSum = Math.Max(MaxSum, sum);
    MinSum = Math.Min(MinSum, sum);
 
    // Decrement sum by arr[start]
    // and increment start by 1
    sum -= arr[start++];
 
    // Traverse arr for the
    // remaining subarrays
    while (i < N)
    {
 
        // Increment sum by arr[i]
        sum += arr[i];
 
        // Increment i
        i++;
 
        // Update maxSum and minSum
        MaxSum = Math.Max(MaxSum, sum);
        MinSum = Math.Min(MinSum, sum);
 
        // Decrement sum by arr[start]
        // and increment start by 1
        sum -= arr[start++];
    }
 
    // Return absolute difference
    // between maxSum and minSum
    return Math.Abs(MaxSum - MinSum);
}
 
// Driver code
public static void Main(String[] args)
{
    int[] arr = { -2, -3, 4, -1,
                  -2, 1, 5, -3 };
    int K = 3;
    int N = arr.Length;
    Console.Write(MaxAbsSumOfKsubArray(arr, K, N));
}
}
 
// This code is contributed
// by shivanisinghss2110


Javascript


输出:
6

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

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。