Longest subarray with only one value greater than k

Given an array of N numbers, find length of the longest subarray such that K is the second largest element on insertion.

Examples:

Input: a[] = {9, 5, 5, 6, 8}, K = 7
Output: 4
The longest subarray is {9, 5, 5, 6}, in which if K is inserted it becomes {9, 5, 5, 6, 7}, and
7 is the second largest element in the array

Input: a[] = {9, 5, 5, 6, 8}, K = 10
Output: 0
Since the maximum number in the array is less than that of K, hence it is not possible.

Input: a[] = {8, 5, 10, 10, 8}, K = 9
Output: 5
9 is the second largest element of whole array

A naive approach is to iterate for every possible subarray and check if on insertion of K, it becomes the second largest element or not. Naively we can store the length of the longest of all such subarrays possible.

Time Complexity: O(N^2)

An efficient solution is to to use the two pointer technique to solve the above problem. Below is the algorithm to solve the above problem.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the length of the longest
// subarray such that K is the second largest element
// on insertion
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the length of longest subarray
int lengthOfLongestSubarray(int a[], int n, int k)
{
    bool flag = 0;
  
    // Check if any element exists which is
    // greater than k or not
    for (int i = 0; i < n; i++) {
        if (a[i] > k)
            flag = 1;
    }
  
    if (!flag) {
        return 0;
    }
  
    // two pointers used
    int front = 0;
    int end = 0;
  
    // find the maximum length
    int maxi = 0;
  
    // Map used to count frequencies
    unordered_map<int, int> mpp;
  
    // set used to find the second largest
    // element in range front-end
    set<int> s;
  
    // initialize all index of array as 0
    bool vis[n];
    memset(vis, 0, sizeof vis);
  
    // iterate till any of the pointer exceeds N
    while (front < n && end < n) {
  
        // length of longest subarray
        maxi = max(maxi, end - front);
  
        // if the current index has not been
        // visited previously then insert it
        // in the set and increase the frequency
        // and mark it as visited.
        if (!vis[end]) {
            mpp[a[end]]++;
            s.insert(a[end]);
            vis[end] = 1;
        }
  
        // find the largest element in the set
        auto it = s.end();
  
        // if only one element is there in set,
        // then insertion of K is possible which
        // will include other elements
        if (s.size() == 1) {
  
            // increase the second pointer in order
            // to include more elements in the subarray
            end++;
            continue;
        }
  
        // twice decrease the
        // iterator as s.end() points to
        // after the last element
        it--;
  
        // second largest element in set
        it--;
        int el = *it;
  
        // if the second largest element is greater than the
        // K, then it is not possible to insert element
        // in range front-end, and thus decrease the
        // frequency of a[front] and remove from set
        // accordingly
        if (el > k) {
            if (mpp[a[front]] == 1) {
                s.erase(a[front]);
                mpp[a[front]]--;
            }
            else
                mpp[a[front]]--;
  
            // move ahead the first pointer
            front++;
        }
        else {
  
            // increase the second pointer
            // if the second largest element is smaller
            // than or equals to K
            end++;
        }
    }
  
    // at then end also check for last subarray length
    maxi = max(maxi, end - front);
  
    return maxi;
}
  
// Driver Code
int main()
{
    int a[] = { 9, 5, 5, 6, 8 };
    int n = sizeof(a) / sizeof(a[0]);
    int k = 7;
  
    cout << lengthOfLongestSubarray(a, n, k);
  
    return 0;
}
chevron_right

Output:
4

Time Complexity: O(N * log N)




Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :