![]() |
VOOZH | about |
Given an array arr[] of costs, your task is to minimize the sum of the absolute differences between consecutive costs by performing following operation at mostonce. Operation is that, we can select any index 'i' then make arr[i] = arr[i]/2.
Example:
Input: arr= [4,9,8]
Output: 4
Explanation: At index 0, 4 is halved now the array looks like = [2,9,8] and sum of absolute difference is abs(2-abs (9-8)= 8
At index 1, 9 is halved now the array looks like =[4,4,8] and sum of absolute difference is abs(4-abs (4-8)= 4
At index 2 8 is halved now the array looks like = [4,9,4] and sum of absolute difference is abs(4-abs (9-4)= 10
minimum of all absolute sums is 4.Input: arr= [99,102,1,45,65]
Output: 161
Explanation: At index 0, 99 is halved now the array looks like = [49,102,1,45,65] and sum of absolute difference is 218
At index 1, 102 is halved now the array looks like = [99,51,1,45,65] and sum of absolute difference is 162
At index 2, 1 is halved now the array looks like = [99,102,0,45,65] and sum of absolute difference is 170
At index 3, 45 is halved now the array looks like = [99,102,1,22,65] and sum of absolute difference is 168
At index 4, 65 is halved now the array looks like = [99,102,1,45,32] and sum of absolute difference is 161
Approach:
We can solve this problem by just iterating the elements of an array and apply the operation on the element and store the minimum answer in any variable, this minimum value will be our resultant answer.
Steps to solve this problem:
Below is the implementation of the above problem:
161
Time Complexity: O(n)
Auxiliary space: O(n)