Maximum sum of lengths of non-overlapping subarrays with k as the max element.
Last Updated :
12 Oct, 2022
Find the maximum sum of lengths of non-overlapping subarrays (contiguous elements) with k as the maximum element.
Examples:
Input : arr[] = {2, 1, 4, 9, 2, 3, 8, 3, 4}
k = 4
Output : 5
{2, 1, 4} => Length = 3
{3, 4} => Length = 2
So, 3 + 2 = 5 is the answer
Input : arr[] = {1, 2, 3, 2, 3, 4, 1}
k = 4
Output : 7
{1, 2, 3, 2, 3, 4, 1} => Length = 7
Input : arr = {4, 5, 7, 1, 2, 9, 8, 4, 3, 1}
k = 4
Ans = 4
{4} => Length = 1
{4, 3, 1} => Length = 3
So, 1 + 3 = 4 is the answer
Question source : https://www.geeksforgeeks.org/amazon-interview-experience-set-376-campus-internship/
Algorithm :
Traverse the array starting from first element
Take a loop and keep on incrementing count
If element is less than equal to k
if array element is equal to k, then mark
a flag
If flag is marked, add this count to answer
Take another loop and traverse the array
till element is greater than k
return ans
Implementation:
C++
// CPP program to calculate max sum lengths of
// non overlapping contiguous subarrays with k as
// max element
#include <bits/stdc++.h>
using namespace std;
// Returns max sum of lengths with maximum element
// as k
int calculateMaxSumLength(int arr[], int n, int k)
{
int ans = 0; // final sum of lengths
// number of elements in current subarray
int count = 0;
// variable for checking if k appeared in subarray
int flag = 0;
for (int i = 0; i < n;) {
count = 0;
flag = 0;
// count the number of elements which are
// less than equal to k
while (arr[i] <= k && i < n) {
count++;
if (arr[i] == k)
flag = 1;
i++;
}
// if current element appeared in current
// subarray add count to sumLength
if (flag == 1)
ans += count;
// skip the array elements which are
// greater than k
while (arr[i] > k && i < n)
i++;
}
return ans;
}
// driver program
int main()
{
int arr[] = { 4, 5, 7, 1, 2, 9, 8, 4, 3, 1 };
int size = sizeof(arr) / sizeof(arr[0]);
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
cout << "Max Length :: " << ans << endl;
return 0;
}
Java
// A Java program to calculate max sum lengths of
// non overlapping contiguous subarrays with k as
// max element
public class GFG
{
// Returns max sum of lengths with maximum element
// as k
static int calculateMaxSumLength(int arr[], int n, int k) {
int ans = 0; // final sum of lengths
// number of elements in current subarray
int count = 0;
// variable for checking if k appeared in subarray
int flag = 0;
for (int i = 0; i < n;) {
count = 0;
flag = 0;
// count the number of elements which are
// less than equal to k
while (i < n && arr[i] <= k) {
count++;
if (arr[i] == k)
flag = 1;
i++;
}
// if current element appeared in current
// subarray add count to sumLength
if (flag == 1)
ans += count;
// skip the array elements which are
// greater than k
while (i < n && arr[i] > k)
i++;
}
return ans;
}
// driver program to test above method
public static void main(String[] args) {
int arr[] = { 4, 5, 7, 1, 2, 9, 8, 4, 3, 1 };
int size = arr.length;
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
System.out.println("Max Length :: " + ans);
}
}
// This code is contributed by Sumit Ghosh
Python3
# Python program to calculate max sum lengths of non
# overlapping contiguous subarrays with k as max element
# Returns max sum of lengths with max elements as k
def calculateMaxSumLength(arr, n, k):
ans = 0 # final sum of lengths
i=0
while i < n :
# number of elements in current sub array
count = 0
# Variable for checking if k appeared in the sub array
flag = 0
# Count the number of elements which are
# less than or equal to k
while i < n and arr[i] <= k :
count = count + 1
if arr[i] == k:
flag = 1
i = i + 1
# if current element appeared in current
# subarray and count to sumLength
if flag == 1:
ans = ans + count
# skip the array elements which are greater than k
while i < n and arr[i] > k :
i = i + 1
return ans
# Driver Program
arr = [4, 5, 7, 1, 2, 9, 8, 4, 3, 1]
size = len(arr)
k = 4
ans = calculateMaxSumLength(arr, size, k)
print ("Max Length ::",ans)
# Contributed by Rohit
C#
// A C# program to calculate max
// sum lengths of non overlapping
// contiguous subarrays with k as
// max element
using System;
class GFG {
// Returns max sum of lengths
// with maximum element as k
static int calculateMaxSumLength(int []arr,
int n,
int k)
{
// final sum of lengths
int ans = 0;
// number of elements in
// current subarray
int count = 0;
// variable for checking if
// k appeared in subarray
int flag = 0;
for(int i = 0; i < n;)
{
count = 0;
flag = 0;
// count the number of
// elements which are
// less than equal to k
while (i < n && arr[i] <= k)
{
count++;
if (arr[i] == k)
flag = 1;
i++;
}
// if current element
// appeared in current
// subarray add count
// to sumLength
if (flag == 1)
ans += count;
// skip the array
// elements which are
// greater than k
while (i < n && arr[i] > k)
i++;
}
return ans;
}
// Driver Code
public static void Main()
{
int []arr = {4, 5, 7, 1, 2, 9, 8, 4, 3, 1};
int size = arr.Length;
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
Console.WriteLine("Max Length :: " + ans);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to calculate max sum lengths
// of non overlapping contiguous subarrays
// with k as max element
// Returns max sum of lengths with maximum
// element as k
function calculateMaxSumLength(&$arr, $n, $k)
{
$ans = 0; // final sum of lengths
// number of elements in current subarray
$count = 0;
// variable for checking if k
// appeared in subarray
$flag = 0;
for ($i = 0; $i < $n;)
{
$count = 0;
$flag = 0;
// count the number of elements which
// are less than equal to k
while ($arr[$i] <= $k && $i < $n)
{
$count++;
if ($arr[$i] == $k)
$flag = 1;
$i++;
}
// if current element appeared in current
// subarray add count to sumLength
if ($flag == 1)
$ans += $count;
// skip the array elements which are
// greater than k
while ($arr[$i] > $k && $i < $n)
$i++;
}
return $ans;
}
// Driver Code
$arr = array( 4, 5, 7, 1, 2,
9, 8, 4, 3, 1 );
$size = sizeof($arr);
$k = 4;
$ans = calculateMaxSumLength($arr, $size, $k);
echo "Max Length :: " . $ans . "\n";
// This code is contributed by ita_c
?>
JavaScript
<script>
// A Javascript program to calculate max sum lengths of
// non overlapping contiguous subarrays with k as
// max element
// Returns max sum of lengths with maximum element
// as k
function calculateMaxSumLength(arr,n,k)
{
let ans = 0; // final sum of lengths
// number of elements in current subarray
let count = 0;
// variable for checking if k appeared in subarray
let flag = 0;
for (let i = 0; i < n;) {
count = 0;
flag = 0;
// count the number of elements which are
// less than equal to k
while (i < n && arr[i] <= k) {
count++;
if (arr[i] == k)
flag = 1;
i++;
}
// if current element appeared in current
// subarray add count to sumLength
if (flag == 1)
ans += count;
// skip the array elements which are
// greater than k
while (i < n && arr[i] > k)
i++;
}
return ans;
}
// driver program to test above method
let arr=[4, 5, 7, 1, 2, 9, 8, 4, 3, 1];
let size = arr.length;
let k = 4;
let ans = calculateMaxSumLength(arr, size, k);
document.write("Max Length :: " + ans);
//This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n), It may look like O(n2), but if you take a closer look, array is traversed only once
Auxiliary Space: O(1)
Another approach:
Algorithm:
Traverse the array from first element to last element
if the element is less than k increment the count
if the element is equals to k
if k is not found
increment the count and mark flag as 1
if k is found
add the value of count to ans and mark count as 1
if the element is greater than k
if k is present in the subarray add the value of count to ans and
assign value of count and flag variables as 0
finally check again if k value is found in subarray or not
if k is found return sum of answer and count
if not return ans
Implementation:
C++
// C++ program to find Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
#include <bits/stdc++.h>
using namespace std;
// Below function calculates the Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
int calculateMaxSumLength(int arr[], int n, int k)
{
// maximum sum of lengths
int ans = 0;
// number of elements in current subarray
int count = 0;
// flag variable for checking if k is present
// in current subarray or not
int flag = 0;
for (int i = 0; i < n; i++) {
// increment the count if element in arr is less
// than k
if (arr[i] < k) {
count++;
}
// if the element is equals to k
else if (arr[i] == k) {
if (flag == 0) {
count++;
flag = 1;
}
// if flag is 1, we can say k is already present
// in that subarray. So, add the value of count
// to ans variable and make the count value as 1
// because we found the k
else {
ans += count;
count = 1;
}
}
// if element in arr is greater than k
else {
// if k is present in the subarray
// add the value of count to ans variable
if (flag == 1) {
ans += count;
}
// assign value of count and flag variables as 0
count = 0;
flag = 0;
}
}
// Check again if k value is found in subarray
// if k is found, return sum of values of variables ans
// and count if k is not found, return value of variable
// ans.
if (flag == 1) {
return ans + count;
}
return ans;
}
// driver program
int main()
{
int arr[] = { 4, 5, 7, 1, 2, 9, 8, 4, 3, 1 };
int size = sizeof(arr) / sizeof(arr[0]);
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
cout << "Max Length :: " << ans << endl;
return 0;
}
// Contributed by Ravi Teja Kuchipudi
Java
// JAVA program to find Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
class GFG {
// Below function calculates the Maximum sum of lengths
// of non-overlapping subarrays with k as the max
// element.
static int calculateMaxSumLength(int arr[], int n,
int k)
{
// maximum sum of lengths
int ans = 0;
// number of elements in current subarray
int count = 0;
// flag variable for checking if k is present
// in current subarray or not
int flag = 0;
for (int i = 0; i < n; i++) {
// increment the count if element in arr is less
// than k
if (arr[i] < k) {
count++;
}
// if the element is equals to k
else if (arr[i] == k) {
// if flag is equals to 0 then make flag
// variable value as 1 and increment the
// count.
if (flag == 0) {
count++;
flag = 1;
}
// if flag is 1, we can say k is already
// present in that subarray. So, add the
// value of count to ans variable and make
// the count value as 1 because we found the
// k
else {
ans += count;
count = 1;
}
}
// if element in arr is greater than k
else {
// if k is present in the subarray
// add the value of count to ans variable
if (flag == 1) {
ans += count;
}
// assign value of count and flag variables
// as 0
count = 0;
flag = 0;
}
}
// Check again if k value is found in subarray
// if k is found, return sum of values of variables
// ans and count if k is not found, return value of
// variable ans.
if (flag == 1) {
return ans + count;
}
return ans;
}
// driver program to test above method
public static void main(String[] args)
{
int arr[] = { 4, 5, 7, 1, 2, 9, 8, 4, 3, 1 };
int size = arr.length;
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
System.out.println("Max Length :: " + ans);
}
}
// Contributed by Ravi Teja Kuchipudi
Python3
# program to find Maximum sum of lengths of
# non-overlapping subarrays with k as the max element.
def calculateMaxSumLength(arr, n, k):
# maximum sum of lengths
ans = 0
# number of elements in current subarray
count = 0
# flag variable for checking if k is present in current subarray or not
flag = 0
for i in range(n):
# increment the count if element in arr is less than k
if arr[i] < k:
count = count+1
# if the element is equals to k
elif arr[i] == k:
# if flag is equals to 0 then make flag variable value as 1 and
# increment the count.
if flag == 0:
count = count + 1
flag = 1
# if flag is 1, we can say k is already present in that subarray.
# So, add the value of count to ans variable and
# make the count value as 1 because we found the k
else:
ans = ans + count
count = 1
# if element in arr is greater than k
else:
# if k is present in the subarray
# add the value of count to ans variable
if flag == 1:
ans = ans + count
# assign value of count and flag variables as 0
count = 0
flag = 0
# Check again if k value is found in subarray
# if k is found, return sum of values of variables ans and count
# if k is not found, return value of variable ans.
if flag == 1:
return ans + count
return ans
# Driver Program
arr = [4, 5, 7, 1, 2, 9, 8, 4, 3, 1]
size = len(arr)
k = 4
ans = calculateMaxSumLength(arr, size, k)
print("Max Length ::", ans)
# Contributed by Ravi Teja Kuchipudi
C#
// C# program to find Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
using System;
class GFG
{
// Returns max sum of lengths
// with maximum element as k
static int calculateMaxSumLength(int[] arr, int n, int k)
{
// maximum sum of lengths
int ans = 0;
// number of elements in current subarray
int count = 0;
// flag variable for checking if k is present
// in current subarray or not
int flag = 0;
for (int i = 0; i < n; i++)
{
// increment the count if element in arr is less
// than k
if (arr[i] < k)
{
count++;
}
// if the element is equals to k
else if (arr[i] == k)
{
// if flag is equals to 0 then make flag
// variable value as 1 and increment the
// count.
if (flag == 0)
{
count++;
flag = 1;
}
// if flag is 1, we can say k is already
// present in that subarray. So, add the
// value of count to ans variable and make
// the count value as 1 because we found the
// k
else
{
ans += count;
count = 1;
}
}
// if element in arr is greater than k
else
{
// if k is present in the subarray
// add the value of count to ans variable
if (flag == 1)
{
ans += count;
}
// assign value of count and flag variables
// as 0
count = 0;
flag = 0;
}
}
// Check again if k value is found in subarray
// if k is found, return sum of values of variables
// ans and count if k is not found, return value of
// variable ans.
if (flag == 1)
{
return ans + count;
}
return ans;
}
// Driver Code
public static void Main()
{
int []arr = {4, 5, 7, 1, 2, 9, 8, 4, 3, 1};
int size = arr.Length;
int k = 4;
int ans = calculateMaxSumLength(arr, size, k);
Console.WriteLine("Max Length :: " + ans);
}
}
// This code is contributed by kothavvsaakash
JavaScript
<script>
// JavaScript program to find Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
// Below function calculates the Maximum sum of lengths of
// non-overlapping subarrays with k as the max element.
function calculateMaxSumLength(arr, n, k)
{
// maximum sum of lengths
let ans = 0;
// number of elements in current subarray
let count = 0;
// flag variable for checking if k is present
// in current subarray or not
let flag = 0;
for (let i = 0; i < n; i++)
{
// increment the count if element in arr is less
// than k
if (arr[i] < k) {
count++;
}
// if the element is equals to k
else if (arr[i] == k) {
if (flag == 0) {
count++;
flag = 1;
}
// if flag is 1, we can say k is already present
// in that subarray. So, add the value of count
// to ans variable and make the count value as 1
// because we found the k
else {
ans += count;
count = 1;
}
}
// if element in arr is greater than k
else
{
// if k is present in the subarray
// add the value of count to ans variable
if (flag == 1)
{
ans += count;
}
// assign value of count and flag variables as 0
count = 0;
flag = 0;
}
}
// Check again if k value is found in subarray
// if k is found, return sum of values of variables ans
// and count if k is not found, return value of variable
// ans.
if (flag == 1) {
return ans + count;
}
return ans;
}
// driver program
let arr = [ 4, 5, 7, 1, 2, 9, 8, 4, 3, 1 ];
let size = arr.length;
let k = 4;
let ans = calculateMaxSumLength(arr, size, k);
document.write("Max Length :: ",ans,"</br>");
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Maximum Sum of two non-overlapping Subarrays of any length
Given an array A consisting of N integers, the task is to find the maximum sum of two non-overlapping subarrays of any length of the array. Note: You can select empty subarrays also. Examples: Input: N = 3, A[] = {-4, -5, -2}Output: 0Explanation: Two empty subarrays are optimal with maximum sum = 0.
6 min read
Maximum sum of non-overlapping subarrays of length atmost K
Given an integer array 'arr' of length N and an integer 'k', select some non-overlapping subarrays such that each sub-array if of length at most 'k', no two sub-arrays are adjacent and sum of all the elements of the selected sub-arrays are maximum.Examples: Input : arr[] = {-1, 2, -3, 4, 5}, k = 2 O
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
Maximize count of non-overlapping subarrays with sum K
Given an array arr[] and an integer K, the task is to print the maximum number of non-overlapping subarrays with a sum equal to K. Examples: Input: arr[] = {-2, 6, 6, 3, 5, 4, 1, 2, 8}, K = 10Output: 3Explanation: All possible non-overlapping subarrays with sum K(= 10) are {-2, 6, 6}, {5, 4, 1}, {2,
6 min read
Maximum sum two non-overlapping subarrays of given size
Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of
12 min read
Maximum sum of at most K non-overlapping Subarray
Given an array, arr[] of size N, the task is to find the sum of the at most K non-overlapping contiguous subarray within an arr[] with the maximum sum. Examples: Input: arr[] = [4, 1, -3, 7, -5, 6, -2, 1], K = 3Output: 18Explanation: In the above input, the maximum k subarray sum is 18 and the subar
15 min read
Max sum of M non-overlapping subarrays of size K
Given an array and two numbers M and K. We need to find the max sum of sums of M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array si
15+ min read
Maximum non overlapping Subset with sum greater than K
Given an array, arr[] and integer K, the task is to find the maximum number of non-overlapping subsets such that the sum of the subsets is strictly greater than K when you may also change the value of each element to the maximum value of the particular subset. Examples: Input: arr[]= {90, 80, 70, 60
5 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
Count non-overlapping Subarrays of size K with equal alternate elements
Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal. Examples: Input: arr[] = {2, 4, 2, 7}, K = 3Output: 1Explanation: Given subarray {2, 4, 2} is a valid array because the elements in even position(index n
7 min read