[CareerCup][Google Interview] Find kth number in a BST

Given n elements, sort the elements. Here, only one operation is permitted decreaseValue..
Note that you cannot swap the values.. output should be a sorted list..
if input is 4 5 2 1 3
output is 3 3 3.. There can be many answers.. Give the optimum solution with minimum cost. where as cost is the sum of decreased amounts..
for this example, 4,5 are decreased by 1.. 2 is decreased by 2.. 1 is decreased by 1..

 

一开始也想到用DP,但感觉DP需要一个子问题独立,但我似乎怎么看都找不到子问题独立。

最后一位高人给出了神解答

min_cost[a_i+1] = if a_i+1 >= a_i then min_cost[a_i]
else min( min_cost[a_i] + a_i+1, min_cost[a_i] + Summation[(j <- 1..i) (a_j - a_i)])

where a_i, a_i+1 are the i_th and i+1_th element in the considered array.
Can u write a recursive program for this and check? It's 5 in the morning and am not sure of the approach 

关键就在于这个summation,点睛之笔。处理了不想删掉当前数,怎么样去前向处理前面的数。当前面的数在上一个子问题中被删去的时候,这种处理可以完美的解决掉。

所以也就形成了子问题独立,因此可以用DP

posted @ 2012-11-09 21:51  chkkch  阅读(438)  评论(0编辑  收藏  举报