![]() |
VOOZH | about |
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.
Table of Content
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.
7
Time Complexity: O(2^n)
Auxiliary Space: O(n)
The idea is to split the array into contiguous segments containing only elements less than or equal to
k. Elements greater thankact as separators since they cannot be part of a subarray whose maximum element isk. For each segment, if it contains at least one occurrence ofk, add its length to the answer. The sum of lengths of all such segments gives the required result.
7
Time Complexity: O(n)
Auxiliary Space: O(1)