First subarray having sum at least half the maximum sum of any subarray of size K
Last Updated :
25 Nov, 2021
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K.
Examples:
Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3
Output: 6 2 1
Explanation:
The given array has a maximum possible sum from any subarray of size K is 16 from the subarray {4, 6, 6}.
So, the required subarray sum should be greater than or equal to 8
{6, 2, 1} is the first subarray which has a sum of 9 which is greater than 8.
Input: arr[] = {12, 45, 11, 10, 8, 56, 2}, K = 4
Output: 45 11 10
Approach: This problem can be solved using the sliding windows technique because subarrays are to be taken into consideration. Follow the steps below to solve this problem:
- Calculate the sum of all subarrays of size K and store them in an array.
- Now, find the maximum of all the sums.
- Iterate over the array and find a sum that is greater than or equal to half of the maximum subarray sum obtained above.
- Print the subarray satisfying the above condition.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
#include <iostream>
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<int> 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<int> 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<Integer> 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<Integer> 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<int> res = new List<int>();
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<int> copy = new List<int>(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
<script>
// javascript implementation of
// the above approach
// Creating the bblSort function
function bblSort(arr){
for(var i = 0; i < arr.length; i++){
// Last i elements are already in place
for(var j = 0; j < ( arr.length - i -1 ); j++){
// Checking if the item at present iteration
// is greater than the next iteration
if(arr[j] > arr[j+1]){
// If the condition is true then swap them
var temp = arr[j]
arr[j] = arr[j + 1]
arr[j+1] = temp
}
}
}
// Print the sorted array
return arr;
}
// Function to print the subarray with sum
// greater or equal than the half of
// the maximum subarray sum of K size
function subArray(arr , n , k) {
var sum = 0;
// Storing sum of first subarray
for (i = 0; i < k; i++) {
sum += arr[i];
}
// Vector to store the
// subarray sums
var res =[];
res.push(sum);
// Sliding window technique to
// Find sum of subarrays of size K
for (i = k; i < n; i++) {
sum -= arr[i - k];
sum += arr[i];
res.push(sum);
}
// Maximum sub-array sum
var max_sum = res[0];
for (i = 0; i < res.length; i++) {
if (max_sum < res[i]) {
max_sum = res[i];
}
}
var half = max_sum / 2;
// Create a copy vector
var copy = Array(res.length).fill(0);
for (i = 0; i < res.length; i++)
copy[i] = res[i];
// Sort the vector
copy = bblSort(copy);
var half_index = 0, half_sum = 0;
// Check in a sorted array for
// an element exceeding
// half of the max_sum
for (x = 0; x < copy.length; x++) {
if (copy[x] >= half) {
half_sum = copy[x];
break;
}
}
// Calculate index of first
// subarray having required sum
for (x = 0; x < res.length; x++) {
if (res[x] == half_sum) {
half_index = x;
break;
}
}
// Print the subarray
for (i = 1; i <= k; i++) {
document.write(arr[half_index + i - 1] + " ");
}
}
// Driver Code
// Given array
var arr = [ 2, 4, 5, 1, 4, 6, 6, 2, 1, 0 ];
var k = 3;
var n = arr.length;
// Function Call
subArray(arr, n, k);
// This code is contributed by todaysgaurav
</script>
Time complexity: O(NlogN)
Space Complexity: O(N)
Similar Reads
Maximum subarray size having all subarrays sums less than k Given an array of positive integers arr[] of size n, and an integer k. The task is to find the maximum subarray size such that all subarrays of that size have sum less than or equals to k.Examples : Input : arr[] = [1, 2, 3, 4], k = 8.Output : 2Explanation: Following are the sum of subarray of size
15+ min read
Maximize the subarray sum by choosing M subarrays of size K Given an array arr containing N positive integers, and two integers K and M, the task is to calculate the maximum sum of M subarrays of size K. Example: Input: arr[] = {1, 2, 1, 2, 6, 7, 5, 1}, M = 3, K = 2Output: 33Explanation: The three chosen subarrays are [2, 6], [6, 7] and [7, 5] respectively.
6 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print
10 min read
Maximize the sum of maximum elements of at least K-sized subarrays Given an integer array arr[] of length N and an integer K, partition the array in some non-overlapping subarrays such that each subarray has size at least K and each element of the array should be part of a subarray. The task is to maximize the sum of maximum elements across all the subarrays. Examp
7 min read
Split the array into N subarrays where each subarray has size 1 or sum at least K Given an array arr[] of size N and integer K. Task for this problem is to check if given array can be split into N continuous subarrays by performing given operations. In one operation choose existing array which may be result of previous operation and split it into two subarrays with each of subarr
10 min read
Split into K subarrays to minimize the maximum sum of all subarrays Given an array arr[] and a number k, split the given array into k subarrays such that the maximum subarray sum achievable out of k subarrays formed is the minimum possible. The task is to find that possible subarray sum.Examples:Input: arr[] = [1, 2, 3, 4], k = 3 Output: 4 Explanation: Optimal Split
11 min read
Maximum sum of subarrays having distinct elements of length K Given an array, arr[] and a value k, represent the length of the subarray to be considered. Find the maximum sum that can be obtained from the subarray of length k such that each element of the subarray is unique. If there is no subarray that meets the required condition then return 0. Examples: Inp
13 min read
Maximum sum subarray having sum less than given sum using Set Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than
7 min read
Maximum sum subarray having sum less than or equal to given sum You are given an array of non-negative integers and a target sum. Your task is to find a contiguous subarray whose sum is the maximum possible, while ensuring that it does not exceed the given target sum.Note: The given array contains only non-negative integers.Examples: Input: arr[] = [1, 2, 3, 4,
6 min read
Maximum count of distinct sized subarrays with given sum Given a binary array arr[] of N integers, the task is to find the maximum count of distinct sized subarrays such that the sum of each subarray is K. Example: Input: arr[] = {0, 1, 1 , 0}, K = 2Output: 3Explanation: The subset {{0, 1, 1, 0}, {0, 1, 1}, {1, 1}} is the subset of 3 subarrays such that t
7 min read