📌  相关文章
📜  第一个子数组的总和至少是大小为 K 的任何子数组的最大总和的一半

📅  最后修改于: 2021-09-08 12:44:22             🧑  作者: Mango

给定一个数组arr[]和一个整数K ,任务是从大小为K 的任何子数组中找到总和大于或等于最大可能总和的一半的第一个子数组。

例子:

方法:这个问题可以使用滑动窗口技术解决,因为要考虑子阵列。请按照以下步骤解决此问题:

  1. 计算所有大小为K 的子数组的总和并将它们存储在一个数组中。
  2. 现在,找出所有和的最大值。
  3. 遍历数组并找到大于或等于上面获得的最大子数组总和的一半的总和。
  4. 打印满足上述条件的子数组。

下面是上述方法的实现:

C++
// C++ implementation of the above approach
#include 
#include 
using namespace std;
 
// Function to print the subarray with sum
// greater or equal than the half of
// the maximum subarray sum of K size
void subArray(int arr[], int n, int k)
{
    int sum = 0;
 
    // Storing sum of first subarray
    for (int i = 0; i < k; i++) {
        sum += arr[i];
    }
 
    // Vector to store the
    // subarray sums
    vector res;
    res.push_back(sum);
 
    // Sliding window technique to
    // Find sum of subarrays of size K
    for (int i = k; i < n; i++) {
        sum -= arr[i - k];
        sum += arr[i];
        res.push_back(sum);
    }
 
    // Maximum sub-array sum
    int max_sum = *max_element(res.begin(),
                               res.end());
 
    int half = max_sum / 2;
 
    // Create a copy vector
    vector copy = res;
 
    // Sort the vector
    sort(copy.begin(),copy.end()); 
   
    int half_index, half_sum;
 
    // Check in a sorted array for
    // an element exceeding
    // half of the max_sum
    for (auto x : copy) {
        if (x >= half) {
            half_sum = x;
            break;
        }
    }
 
    // Calculate index of first
    // subarray having required sum
    for (int x = 0; x < res.size(); x++) {
        if (res[x] == half_sum) {
            half_index = x;
            break;
        }
    }
 
    // Print the subarray
    for (int i = 1; i <= k; i++) {
        cout << arr[half_index + i - 1]
             << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 2, 4, 5, 1, 4, 6, 6, 2, 1, 0 };
    int k = 3;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    subArray(arr, n, k);
 
    return 0;
}
// This code is contributed by akshitdiwan05


Java
// Java implementation of
// the above approach
import java.util.*;
class GFG{
 
// Function to print the subarray with sum
// greater or equal than the half of
// the maximum subarray sum of K size
static void subArray(int arr[],
                     int n, int k)
{
  int sum = 0;
 
  // Storing sum of first subarray
  for (int i = 0; i < k; i++)
  {
    sum += arr[i];
  }
 
  // Vector to store the
  // subarray sums
  Vector res = new Vector<>();
  res.add(sum);
 
  // Sliding window technique to
  // Find sum of subarrays of size K
  for (int i = k; i < n; i++)
  {
    sum -= arr[i - k];
    sum += arr[i];
    res.add(sum);
  }
 
  // Maximum sub-array sum
  int max_sum = res.elementAt(0);
  for(int i =0; i < res.size(); i++)
  {
    if(max_sum < res.elementAt(i))
    {
      max_sum = res.elementAt(i);
    }
  }
 
  int half = max_sum / 2;
 
  // Create a copy vector
  Vector copy =
                  new Vector<>(res);
 
  // Sort the vector
  Collections.sort(copy);
  int half_index = 0, half_sum = 0;
 
  // Check in a sorted array for
  // an element exceeding
  // half of the max_sum
  for (int x = 0; x < copy.size(); x++)
  {
    if (copy.elementAt(x) >= half)
    {
      half_sum = copy.elementAt(x);
      break;
    }
  }
 
  // Calculate index of first
  // subarray having required sum
  for (int x = 0; x < res.size(); x++)
  {
    if (res.elementAt(x) == half_sum)
    {
      half_index = x;
      break;
    }
  }
 
  // Print the subarray
  for (int i = 1; i <= k; i++)
  {
    System.out.print(
           arr[half_index + i - 1] + " ");
  }
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array
  int arr[] = {2, 4, 5, 1, 4,
               6, 6, 2, 1, 0};
  int k = 3;
  int n = arr.length;
 
  // Function Call
  subArray(arr, n, k);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python 3 implementation
# of the above approach
 
# Function to print the
# subarray with sum greater
# or equal than the half of
# the maximum subarray
# sum of K size
def subArray(arr, n, k):
 
    sum = 0
 
    # Storing sum of
    # first subarray
    for i in range (k):
        sum += arr[i]
    
    # Vector to store the
    # subarray sums
    res = []
    res.append(sum)
 
    # Sliding window technique
    # to find sum of subarrays
    # of size K
    for i in range (k, n):
        sum -= arr[i - k]
        sum += arr[i]
        res.append(sum)
    
    # Maximum sub-array sum
    max_sum = max(res)
    half = max_sum // 2
 
    # Create a copy vector
    copy = res.copy()
 
    # Sort the vector
    copy.sort()
  
    # Check in a sorted array for
    # an element exceeding
    # half of the max_sum
    for x in copy:
        if (x >= half):
            half_sum = x
            break
       
    # Calculate index of first
    # subarray having required sum
    for x in range (len(res)):
        if (res[x] == half_sum):
            half_index = x
            break
     
    # Print the subarray
    for i in range (1, k + 1):
        print (arr[half_index + i - 1] ,
               end = " ")
 
# Driver Code
if __name__ == "__main__":
   
    # Given array
    arr = [2, 4, 5, 1, 4,
           6, 6, 2, 1, 0]
    k = 3
    n = len(arr)
 
    # Function Call
    subArray(arr, n, k);
 
# This code is contributed by Chitranayal


C#
// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to print the subarray with sum
// greater or equal than the half of
// the maximum subarray sum of K size
static void subArray(int []arr,
                     int n, int k)
{
    int sum = 0;
     
    // Storing sum of first subarray
    for(int i = 0; i < k; i++)
    {
        sum += arr[i];
    }
     
    // List to store the
    // subarray sums
    List res = new List();
    res.Add(sum);
     
    // Sliding window technique to
    // Find sum of subarrays of size K
    for(int i = k; i < n; i++)
    {
        sum -= arr[i - k];
        sum += arr[i];
        res.Add(sum);
    }
     
    // Maximum sub-array sum
    int max_sum = res[0];
    for(int i = 0; i < res.Count; i++)
    {
        if (max_sum < res[i])
        {
            max_sum = res[i];
        }
    }
     
    int half = max_sum / 2;
     
    // Create a copy vector
    List copy = new List(res);
     
    // Sort the vector
    copy.Sort();
    int half_index = 0, half_sum = 0;
     
    // Check in a sorted array for
    // an element exceeding
    // half of the max_sum
    for(int x = 0; x < copy.Count; x++)
    {
        if (copy[x] >= half)
        {
            half_sum = copy[x];
            break;
        }
    }
     
    // Calculate index of first
    // subarray having required sum
    for(int x = 0; x < res.Count; x++)
    {
        if (res[x] == half_sum)
        {
            half_index = x;
            break;
        }
    }
     
    // Print the subarray
    for(int i = 1; i <= k; i++)
    {
        Console.Write(
            arr[half_index + i - 1] + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 2, 4, 5, 1, 4,
                  6, 6, 2, 1, 0 };
    int k = 3;
    int n = arr.Length;
     
    // Function call
    subArray(arr, n, k);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出
6 2 1 

时间复杂度: O(NlogN)
空间复杂度: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live