Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++


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.

Example

Program to illustrate the working of our solution,

 Live Demo

#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;
}

Output

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

Updated on: 03-Jun-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements