Problem Solution

1 solutions

  • 2
    @ 2024-03-12 08:47:39

    greedy method

    we can iterate over the array from left to right to find all valid perfect subarray and update the maximum size into answer in the following way..

    • if '1' is found and we dont have any index of '1' stored then store the index
    • if '2' is found delete the index of '1' if it was stored
    • if '3' is found and we have a index of '1' stored then update the answer which is (index_of_3 - index_of_1 + 1)

    time complexity O(N)

    binary search

    Since our perfect subarray starts with the value 1 , we can iterate over all possible starting points of perfect subarray and find a valid end point with binary search.
    to do so, we will store all the indexes of 1,2 and 3 in three different vector(named as ONE,TWO,THREE) . it is obvious that all three vectors will be sorted since we will take them from left to right and push them into vector.

    then each time we select an index from vector ONE lets say L, and perform a binary search in the vector TWO to find smallest index of 2 greater than L, lets say R. so we are guaranteed that there are no 2 present in range L to R. after that we will perform another binary search on vector THREE to find the biggest index in between L and R. if we find any index such as K, we will update our answer as (K-L+1) which is the length of the subarray.

    time complexity O(NlogN)

  • 1

Information

ID
1036
Difficulty
6
Category
Beginners Click to Show
Tags
(None)
# Submissions
19
Accepted
9
Accepted Ratio
47%
Uploaded By