![]() |
VOOZH | about |
Given an array arr[] of size n, the task is to count the number of unique differences between the two maximum elements of every subarray of size at least 2 of the given array.
Examples:
Input: arr[] = { 5, 1, 3 }, n = 3
Output: 2
Explanation: The subarrays are {5, 1}, {5, 1, 3}, {1, 3}.
{5, 1} - First max = 5; Second max = 1; difference = (5 - 1) = 4
{5, 1, 3} - First max = 5; Second max = 3; difference = (5 - 3) = 2
{1, 3} - First max = 3; Second max = 1; difference = (3 - 1) = 2
Unique height differences are {4, 2} = 2Input: arr[] = {5, 2, 3, 8}, n = 4
Output: 4
Explanation: The subarrays are: {5, 2}, {5, 2, 3}, {5, 2, 3, 8}, {2, 3}, {2, 3, 8}, {3, 8}
{5, 2} - First max = 5; Second max = 2; difference = (5 - 2) = 3
{5, 2, 3} - First max = 5; Second max = 3; difference = (5 - 3) = 2
{5, 2, 3, 8} - First max = 8; Second max = 5; difference = (8 - 5) = 3
{2, 3} - First max = 3; Second max = 2; difference = (3 - 2) = 1
{2, 3, 8} - First max = 8; Second max = 3; difference = (8 - 3) = 5
{3,8} - First max = 8; Second max = 3; difference = (8 - 3) = 5
Unique height differences are {3, 2, 1, 5} = 4
The simplest approach is to generate all subarrays while keeping track of the first and second maximum elements. Store all the differences in a set to obtain the count of distinct values. Follow these steps to solve the problem:
- Loop through the array from 0 to n-1 (denoted as i).
- Use a nested loop to iterate from i+1 to n (denoted as j).
- If
firstMax < arr[j], updatesecondMaxtofirstMaxand setfirstMaxtoarr[j].- If
secondMax < arr[j], updatesecondMaxtoarr[j].- Insert the difference
firstMax - secondMaxinto a set.- Return the size of the set as the final result.
2
The problem can be solved based on the following observation: For each subarray, only the first and second maximum elements are needed. When a new maximum element is added to the subarray, the maximum values need to be updated. This can be efficiently implemented using a stack. Follow these steps to solve the problem:
- Store the next greater element to the left and the next greater element to the right of each array element in two separate arrays.
- Compute the difference between the next greater element to the left and the current element, as well as the difference between the next greater element to the right and the current element.
- Store these differences in a set to ensure only unique values are retained.
- Finally, print the size of the set, which gives the count of unique differences.
2