Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Minimum Total Cost Given an array of integers, the goal is to make all the elements in the array have equal values by applying some

Minimum Total Cost
Given an array of integers, the goal is to make all the elements in the array have equal values by applying
some number of operations.
The rules of the operations are:
To apply an operation, one needs to choose a prefix of the array and an integer x(x can be negative).
In this operation, add x to each element inside this prefix.
The cost of this operation is ?x/(Absolute value of x).
For example, if the array is 1,4,2,1 and the prefix of length 2 and x=-3 are chosen, the array would
now become -2,1,2,1 and the cost of this operation would be |x|=|-3|=3.
The total cost is the sum of costs of each operation applied. Find the minimum total cost of making all
the elements in the array have equal value.
Note: It is guaranteed that there always exists a series of operations by which all the elements in any
array can be equal. These operations can be applied any number of times.
Example
Consider n=4 and arr =[1,2,1,5].
The array can be made equal using the following three operations:
Choose the prefix of length 2 and x=-1, Hence the array now becomes 0,1,1,5. The cost of this operation
is |x|=|-1|=1
Choose the prefix of length 3 and x=4, Hence the array now becomes 4,5,5,5. The cost of this operation is
|x|=|4|=4
Choose the prefix of length 1 and x=1, Hence the array now becomes 5,5,5,5. The cost of this operation is
|x|=|1|=1
Thus, the total cost =1+4+1=6, which is the minimum possible.
Any hint for this?when arr is [1,1,1,1]cost should be zero when arr is [1,2,3,1,2]cost is 5

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Practical Neo4j

Authors: Gregory Jordan

1st Edition

1484200225, 9781484200223

More Books

Students also viewed these Databases questions

Question

What are examples of investment companies?

Answered: 1 week ago