Wednesday, February 8, 2023
HomeSoftware DevelopmentMaximize first worth by simultaneous increment and decrement of components

# Maximize first worth by simultaneous increment and decrement of components

Given an array nums[] of measurement N, Discover the most worth you may 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 < nums[i] (1 ≤ i ≤ N-1). You’ll be able to carry out as many strikes as you desire to (presumably, zero).

Examples:

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

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

Method: The issue may be solved primarily based on the next concept:

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

Comply with the steps talked about under to implement the thought:

• 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, do the given operation
• Worth at index 0 will get elevated by the (nums[i] – nums +1) / 2
• Return the worth at index 0 as the required reply.

Under is the implementation of the above method:

## C++

 ` `  `#embody ` `utilizing` `namespace` `std;` ` `  `int` `maximumValue(vector<``int``>& nums, ``int` `n)` `{` `    ` `    ``int` `value_at_index_0 = nums;` ` `  `    ` `    ` `    ``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` `primary()` `{` `    ``vector<``int``> nums = { 1, 2, 3 };` `    ``int` `N = nums.measurement();` ` `  `    ` `    ``cout << maximumValue(nums, N);` ` `  `    ``return` `0;` `}`

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

Associated Articles:

RELATED ARTICLES