VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-lengths-non-overlapping-subarrays-k-max-element/

⇱ Maximum sum of lengths of non-overlapping subarrays with k as the max - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of lengths of non-overlapping subarrays with k as the max

Last Updated : 13 Jun, 2026

Given an array arr[], the task is to find the maximum sum of lengths of all non-overlapping subarrays with k as the maximum element in the subarray.

Examples:

Input: arr[] = [2, 1, 4, 9, 2, 3, 8, 3, 4], k = 4
Output: 5
Explanation: The non-overlapping subarrays whose maximum element is 4 are:
[2, 1, 4] -> Length = 3,
[3, 4] -> Length = 2,
Therefore, the total length is 3 + 2 = 5.

Input: arr[] = [1, 2, 3, 2, 3, 4, 1], k = 4
Output: 7
Explanation: The entire array [1, 2, 3, 2, 3, 4, 1] has maximum element equal to 4. Hence, the total length is 7.

[Naive Approach] Check Every Subarray - O(2^n) Time O(n) Space

The idea is to try every possible subarray starting from the current index. If a subarray has maximum element equal to k, we can either take it and continue from the next non-overlapping position or skip the current index. The maximum of all such choices gives the answer.


Output
7

Time Complexity: O(2^n)
Auxiliary Space: O(n)

[Expected Approach] Split by Elements Greater than k - O(n) Time O(1) Space

The idea is to split the array into contiguous segments containing only elements less than or equal to k. Elements greater than k act as separators since they cannot be part of a subarray whose maximum element is k. For each segment, if it contains at least one occurrence of k, add its length to the answer. The sum of lengths of all such segments gives the required result.


Output
7

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: