Maximize indices with value more than sum of neighbours
Given an array of integers arr, the task is to find the maximum number of the indices having values greater than the sum of the neighbours after performing the given operation:
- In an operation, you can select K(given) consecutive elements and increase their values by 1.
- This operation can be performed any number of times
Input: arr = [2, 9, 2, 4, 1], K = 2
Explanation: Here arr and arr is fulfilling the criteria.
No matter how many times you increase K consecutive elements,
you cannot get more than 2 such indices.
Input: arr = [3, 1, 3, 4, 5, 1, 2], K = 1
Explanation: We will select K =1 consecutive elements and increment it’s value by 1
Select arr six times then array becomes: [3, 7, 3, 4, 5, 1, 2]
Select arr five times then array becomes: [3, 7, 3, 9, 5, 1, 2]
Select arr seven times then array becomes: [3, 7, 3, 9, 5, 8, 2]
Now arr, arr and arr satisfies the criteria.
Approach: To solve the problem follow the below idea:
This problem deals with finding the maximum count of indices, after performing the given operation any number of times.
Here, if K = 1, then the answer will be equal to the number of elements present at the odd index,
If K > 1 then the answer will be equal to the number of indices that already satisfies the given criteria, as increasing the values of a subarray can never help to get a new index, as the values of its neighbors will also increase.
Follow the given steps to solve the problem:
- If K = 1, then the answer will be the number of elements present at an odd index in arr
- For other values of K, here the answer will be those indices whose arr[i] > arr[i + 1] + arr[i – 1].
- Return the count depending on the value of K.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(1)
Please Login to comment...