- Related Questions & Answers
- Max sum of M non-overlapping subarrays of size K in C++
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Maximum sum two non-overlapping subarrays of given size in C++
- Program to find maximum number of non-overlapping subarrays with sum equals target using Python
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Count of subarrays whose maximum element is greater than k in C++
- Program to find maximum sum of two non-overlapping sublists in Python
- JavaScript Total subarrays with Sum K
- Maximum of all Subarrays of size k using set in C++ STL
- Number of Subarrays with Bounded Maximum in C++
- Maximum Product of Word Lengths in C++
- Count the number of non-increasing subarrays in C++
- Max Sum of Rectangle No Larger Than K in C++
- Program to count non-empty subsets where sum of min and max element of set is less than k in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this problem, we are given an array and an integer k. Our task is to create a program that will find the maximum sum of lengths of non-overlapping subarrays with k as the max element in c++.

**Problem description** − here, we have an array and an integer k. We have to find all possible non-overlapping sub-arrays that can be created from this array. And sum the lengths of all the subarrays created.

Let’s take an example to understand the problem,

**Input** − array = {3, 7, 1, 2, 3, 1, 6, 3, 2, 5} k = 3

**Output** − 7

**Explanation** − non-overlapping subarrays with max element 3:

{3} : length = 1 {1, 2, 3, 1} : length = 4 {3, 2} : length = 2 Sum of length = 1+4+2 = 7

To solve this problem, we will traverse the array and find all elements that are less and maintain a length, if the subarray (the stream of elements) have k then add the length to sum.

Program to illustrate the working of our solution,

#include <iostream> using namespace std; int subArrayLengthSum(int arr[], int n, int k){ int lengthSum = 0; int subarrayLength = 0; int flag = 0; for (int i = 0; i < n;) { subarrayLength = 0; flag = 0; while (arr[i] <= k && i < n) { subarrayLength++; if (arr[i] == k) flag = 1; i++; } if (flag == 1) lengthSum += subarrayLength; while (arr[i] > k && i < n) i++; } return lengthSum; } int main(){ int arr[] = {3, 7, 1, 2, 3, 1, 6, 3, 2, 5}; int size = sizeof(arr) / sizeof(arr[0]); int k = 3; int ans = subArrayLengthSum(arr, size, k); cout<<"The max sum of lengths of non-overlapping subarrays with "<<k<<" as max element is "<<ans; return 0; }

The max sum of lengths of non-overlapping subarrays with 3 as max element is 7

Advertisements