[ad_1]
Given an array arr[] of size N, and an array queries[] of dimension Q, the duty is to search out the variety of lacking components from 1 to most within the vary of indices [L, R] the place L is queries[i][0] and R is queries[i][1].
Examples:
Enter: arr[] = {8, 6, 7, 7, 7}, queries = { {0, 3}, {1, 2}, {0, 2}, {1, 3}, {2, 3} }
Output: 5 5 5 5 6
Rationalization:
Most aspect for vary [0, 3] is 8 so variety of lacking components are 1, 2, 3, 4, 5.
Most aspect for vary [1, 2] is 7 so variety of lacking components are 1, 2, 3, 4, 5.
Most aspect for vary [0, 2] is 8 so variety of lacking components are 1, 2, 3, 4, 5.
Most aspect for vary [1, 3] is 7 so variety of lacking components are 1, 2, 3, 4, 5.
Most aspect for vary [2, 3] is 7 so variety of lacking components are 1, 2, 3, 4, 5, 6.Enter: arr[] = {2, 6, 4, 9}, queries = { {0, 3}, {1, 2}, {0, 2}, {1, 3}, {2, 3} }
Output: 5 4 3 6 7
Rationalization:
Most aspect for vary [0, 3] is 9 so variety of lacking components are 1, 3, 5, 7, 8.
Most aspect for vary [1, 2] is 6 so variety of lacking components are 1, 2, 3, 5.
Most aspect for vary [0, 2] is 6 so variety of lacking components are 1, 3, 5.
Most aspect for vary [1, 3] is 9 so variety of lacking components are 1, 2, 3, 5, 7, 8.
Most aspect for vary [2, 3] is 9 so variety of lacking components are 1, 2, 3, 5, 6, 7, 8.
Strategy: One easy method is to course of each question linearly, retailer all components in a visited map and discover the utmost aspect. Then return the variety of lacking components from 1 to the utmost on that vary.
Observe the beneath steps to resolve this downside:
- Take one unordered map visited.
- Traverse queries from i = 0 to Q-1.
- Initialize one variable to retailer the utmost aspect of the given vary.
- Run once more one for loop from queries[i][0] to queries[i][1].
- Retailer the utmost aspect on this vary.
- Make the visited array 1 for every aspect visited in that vary.
- The variety of lacking components is identical as the worth of (most aspect – variety of distinctive components visited).
Under is the implementation of the above strategy.
C++14
|
Time Complexity: O(Q * N)
Auxiliary Area: O(N)
[ad_2]