[ad_1]
Given an array arr[] of dimension N, the duty is to seek out the utmost worth that may be obtained by following the beneath circumstances:
- Choose any factor (say okay) from the array and enhance all different components by 1.
- Within the subsequent step, soar solely to the index with a price okay+1.
- Ultimately, you’re on the most worth.
Examples:
Enter: N = 4, arr[] ={1, 2, 1, 3}
Output: 3
Clarification: If began from index 0 with a peak of 1 unit, then,
the brand new worth of array might be [1, 3, 2, 4].
Then soar to the index with (1+1 = 2) ie 2nd index,
The up to date values are [2, 4, 2, 5]. Can’t be on the most worth at finish
The primary chosen worth was 3 at index 3.
The up to date values are [2, 3, 2, 3]. Max achieved -3. Therefore ans = 3;Enter: N = 4, arr[]={1, 2, 3, 3}
Output: 4
Strategy: The issue may be solved primarily based on the next commentary:
On commentary, we are able to understand that for reaching most peak we’ve two choices
- Immediately choosing the utmost heighted podium initially accessible.
- Selecting all the weather (say whole y) with similar worth (say x). So highest quantity that may be reached is (x + y – 1).
Comply with the beneath steps to resolve the issue:
- Type the array in growing order.
- Search for the span of the identical worth components and get the utmost worth that may be achieved from that span utilizing the above thought.
- Carry out this for all accessible spans and retailer the utmost.
- Return the most because the required reply.
Beneath is the implementation of the above method.
C++
|
Time Complexity: O(N*logN)
Auxiliary Area: O(1)
[ad_2]