Friday, September 22, 2023
HomeSoftware DevelopmentMost worth you possibly can get hold of at index 0 by...

# Most worth you possibly can get hold of at index 0 by performing given operation

Given an array nums[] of dimension N, Discover the most worth you possibly can obtain at index 0 after performing the operation the place in every operation enhance the worth at index 0 by 1 and reduce the worth at index i by 1 such that nums[0] < nums[i] (1 â‰¤ i â‰¤ N-1). You may carry out as many strikes as you want to (probably, zero).

Examples:

Enter: nums[] = {1, 2, 3}
Output: 3
Rationalization: nums[0] < nums[1], Due to this fact nums[0] + 1 and nums[1] â€“ 1. Now, Â nums[0] = 2, nums[0] < nums[2], once more repeat the step. Now nums[0] turns into 3 which is the utmost potential worth we are able to get at index 0.

Enter: nums[] = {1, 2, 2}
Output: 2

Strategy: The issue will be solved based mostly on the next thought:

With a view to obtain most worth at index 0, kind the array from index 1 to the final index and also can begin iterating it from index 1 and if at any level nums[i] is discovered to be better than the ingredient current at index 0, in line with the given operation nums[0] get elevated and nums[i] get decreased. So, nums[0] get elevated by the quantity (nums[i] â€“ nums[0] + 1) / 2 when encountered with a better worth.

Comply with the steps talked about beneath to implement the concept:

• Retailer the preliminary worth current at index 0 in a variable.
• Type the array from index 1 to the final index.
• Iterate from index 1 and if discovered nums[i] > nums[0], do the given operation
• Worth at index 0 will get elevated by the (nums[i] â€“ nums[0] +1) / 2
• Return the worth at index 0 as the required reply.

Beneath is the implementation of the above method:

## C++

 `Â `Â  `#embrace ` `utilizing` `namespace` `std;` `Â `Â  `int` `maximumValue(vector<``int``>& nums, ``int` `n)` `{` `Â Â Â Â ` `Â Â Â Â ``int` `value_at_index_0 = nums[0];` `Â `Â  `Â Â Â Â ` `Â Â Â Â ` `Â Â Â Â ``kind(nums.start() + 1, nums.finish());` `Â `Â  `Â Â Â Â ` `Â Â Â Â ``for` `(``int` `i = 1; i < n; i++) {` `Â `Â  `Â Â Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ``if` `(nums[i] > value_at_index_0) {` `Â `Â  `Â Â Â Â Â Â Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â Â Â Â Â ``value_at_index_0` `Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ``+= (nums[i] - value_at_index_0 + 1) / 2;` `Â Â Â Â Â Â Â Â ``}` `Â Â Â Â ``}` `Â `Â  `Â Â Â Â ` `Â Â Â Â ``return` `value_at_index_0;` `}` `Â `Â  `int` `principal()` `{` `Â Â Â Â ``vector<``int``> nums = { 1, 2, 3 };` `Â Â Â Â ``int` `N = nums.dimension();` `Â `Â  `Â Â Â Â ` `Â Â Â Â ``cout << maximumValue(nums, N);` `Â `Â  `Â Â Â Â ``return` `0;` `}`

Time Complexity: O(N * log N)
Auxiliary Area: O(1)

Associated Articles:

RELATED ARTICLES