Максимальная длина L такая, что сумма всех подмассивов длины L меньше K

Опубликовано: 5 Января, 2022

Дан массив длины N и целое число K. Задача состоит в том, чтобы найти такую максимальную длину L , чтобы все подмассивы длины L имели сумму элементов меньше K.
Примеры:

Input: arr[] = {1, 2, 3, 4, 5}, K = 20 
Output:
The only subarray of length 5 is the complete 
array and (1 + 2 + 3 + 4 + 5) = 15 < 20.
Input: arr[] = {1, 2, 3, 4, 5}, K = 10 
Output:
 

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Подход: для получения максимальной суммы подмассива длины K используйте подход, описанный в этой статье. Теперь можно выполнить двоичный поиск, чтобы найти максимальную длину. Поскольку элементы массива положительны, увеличение длины подмассива увеличит максимальную сумму элементов подмассива для этой длины.
Ниже представлена реализация описанного выше подхода:

C ++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum sum
// in a subarray of size k
int maxSum( int arr[], int n, int k)
{
// k must be greater
if (n < k) {
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 = max(res, curr_sum);
}
return res;
}
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
int solve( int arr[], int n, int k)
{
int max_len = 0, l = 0, r = n, m;
// Binary search from l to r as all the
// array elements are positive so that
// the maximum subarray sum is monotonically
// increasing
while (l <= r) {
m = (l + r) / 2;
// Check if the subarray sum is
// greater than K or not
if (maxSum(arr, n, m) > k)
r = m - 1;
else {
l = m + 1;
// Update the maximum length
max_len = m;
}
}
return max_len;
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof ( int );
int k = 10;
cout << solve(arr, n, k);
return 0;
}

Джава

// Java implementation of the approach
class GFG
{
// Function to return the maximum sum
// in a subarray of size k
static int maxSum( int arr[], int n, int k)
{
// k must be greater
if (n < k)
{
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;
}
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
static int solve( int arr[], int n, int k)
{
int max_len = 0 , l = 0 , r = n, m;
// Binary search from l to r as all the
// array elements are positive so that
// the maximum subarray sum is monotonically
// increasing
while (l <= r)
{
m = (l + r) / 2 ;
// Check if the subarray sum is
// greater than K or not
if (maxSum(arr, n, m) > k)
r = m - 1 ;
else
{
l = m + 1 ;
// Update the maximum length
max_len = m;
}
}
return max_len;
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 };
int n = arr.length;
int k = 10 ;
System.out.println(solve(arr, n, k));
}
}
// This code is contributed by AnkitRai01

Python3

# Python3 implementation of the approach
# Function to return the maximum sum
# in a subarray of size k
def maxSum(arr, n, k) :
# k must be greater
if (n < k) :
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;
# Function to return the length of subarray
# Sum of all the subarray of this
# length is less than or equal to K
def solve(arr, n, k) :
max_len = 0 ; l = 0 ; r = n;
# Binary search from l to r as all the
# array elements are positive so that
# the maximum subarray sum is monotonically
# increasing
while (l < = r) :
m = (l + r) / / 2 ;
# Check if the subarray sum is
# greater than K or not
if (maxSum(arr, n, m) > k) :
r = m - 1 ;
else :
l = m + 1 ;
# Update the maximum length
max_len = m;
return max_len;
# Driver code
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 , 5 ];
n = len (arr);
k = 10 ;
print (solve(arr, n, k));
# This code is contributed by AnkitRai01

C #

// C# implementation of the approach
using System;
class GFG
{
// Function to return the maximum sum
// in a subarray of size k
static int maxSum( int []arr, int n, int k)
{
// k must be greater
if (n < k)
{
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;
}
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
static int solve( int []arr, int n, int k)
{
int max_len = 0, l = 0, r = n, m;
// Binary search from l to r as all the
// array elements are positive so that
// the maximum subarray sum is monotonically
// increasing
while (l <= r)
{
m = (l + r) / 2;
// Check if the subarray sum is
// greater than K or not
if (maxSum(arr, n, m) > k)
r = m - 1;
else
{
l = m + 1;
// Update the maximum length
max_len = m;
}
}
return max_len;
}
// Driver code
public static void Main ()
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
int k = 10;
Console.WriteLine(solve(arr, n, k));
}
}
// This code is contributed by AnkitRai01

Javascript

<script>
// javascript implementation of the approach
// Function to return the maximum sum
// in a subarray of size k
function maxSum(arr , n , k) {
// k must be greater
if (n < k) {
return -1;
}
// Compute sum of first window of size k
var res = 0;
for (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.
var curr_sum = res;
for (i = k; i < n; i++) {
curr_sum += arr[i] - arr[i - k];
res = Math.max(res, curr_sum);
}
return res;
}
// Function to return the length of subarray
// Sum of all the subarray of this
// length is less than or equal to K
function solve(arr , n , k) {
var max_len = 0, l = 0, r = n, m;
// Binary search from l to r as all the
// array elements are positive so that
// the maximum subarray sum is monotonically
// increasing
while (l <= r) {
m = parseInt((l + r) / 2);
// Check if the subarray sum is
// greater than K or not
if (maxSum(arr, n, m) > k)
r = m - 1;
else {
l = m + 1;
// Update the maximum length
max_len = m;
}
}
return max_len;
}
// Driver code
var arr = [ 1, 2, 3, 4, 5 ];
var n = arr.length;
var k = 10;
document.write(solve(arr, n, k));
// This code contributed by Rajput-Ji
</script>
Выход:
 2

Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .

Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.