I found this question on an online forum: Really interested on how it can be solved:
Given an array A of positive integers. Convert it to a sorted array with minimum cost. The only valid operation are:
1) Decrement with cost = 1
2) Delete an element completely from the array with cost = value of element
This is an interview question asked for a tech company
NOTE : The original answer has been replaced with one in which I have a lot more confidence (and I can explain it, too). Both answers produced the same results on my set of test cases.
You can solve this problem using a dynamic programming approach. The key observation is that it never makes sense to decrement a number to a value not found in the original array. (Informal proof: suppose that you decremented a number
O1to a valueXthat is not in the original sequence in order to avoid removing a numberO2 > Xfrom the result sequence. Then you can decrementO1toO2instead, and reduce the cost byO2-X).Now the solution becomes easy to understand: it is a DP in two dimensions. If we sort the elements of the distinct elements of the original sequence
dinto a sorted arrays, the length ofdbecomes the first dimension of the DP; the length ofsbecomes the second dimension.We declare
dp[d.Length,s.Length]. The value ofdp[i,j]is the cost of solving subproblemd[0 to i]while keeping the last element of the solution unders[j]. Note: this cost includes the cost of eliminatingd[i]if it is less thans[j].The first row
dp[0,j]is computed as the cost of trimmingd[0]tos[j], or zero ifd[0] < s[j]. The value ofdp[i,j]next row is calculated as the minimum ofdp[i-1, 0 to j] + trim, wheretrimis the cost of trimmingd[i]tos[j], ord[i]if it needs to be eliminated becauses[j]is bigger thand[i].The answer is calculated as the minimum of the last row
dp[d.Length-1, 0 to s.Length].Here is an implementation in C#:
This direct implementation has space complexity of
O(N^2). You can reduce it toO(N)by observing that only two last rows are used at the same time.