Given an array which contains integer values, we need to make all values of this array equal to some integer value with minimum cost where the cost of changing an array value x to y is abs(x-y).
Input : arr = [1, 100, 101] Output : 100 We can change all its values to 100 with minimum cost, |1 - 100| + |100 - 100| + |101 - 100| = 100 Input : arr = [4, 6] Output : 2 We can change all its values to 5 with minimum cost, |4 - 5| + |5 - 6| = 2
This problem can be solved by observing the cost while changing the target equal value, i.e. we will see the change in cost when target equal value is changed. It can be observed that, as we increase the target equal value the total cost decreases up to a limit and then starts increasing i.e. the cost graph with respect to target equal value is of U-shape and as cost graph is in U-shape, the ternary search can be applied to this search space and our goal is to get that bottom most point of the curve which will represent the smallest cost. We will make smallest and largest value of the array as the limit of our search space and then we will keep skipping 1/3 part of the search space until we reach to the bottom most point of our U-curve.
Please see below code for better understanding,
Time Complexity : O (n Log n)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum cost to equal all elements of array using two operation
- Minimum operation to make all elements equal in array
- Minimum Bitwise XOR operations to make any two array elements equal
- Minimum operations required to make all the array elements equal
- Minimum Bitwise OR operations to make any two array elements equal
- Minimum value of X to make all array elements equal by either decreasing or increasing by X
- Minimum Bitwise AND operations to make any two array elements equal
- Minimum number of increment-other operations to make all array elements equal.
- Find the minimum number of operations required to make all array elements equal
- Minimum cost to make array size 1 by removing larger of pairs
- Minimum increment by k operations to make all elements equal
- Minimum number of moves to make all elements equal
- Minimum cost of choosing 3 increasing elements in an array of size N
- Make all elements of an array equal with the given operation
- Minimum steps to make the product of the array equal to 1
Improved By : nitin mittal