【題目描述】
Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.
If the array before adjustment isA, the array after adjustment isB, you should minimize the sum of|A[i]-B[i]|
給一個整數數組,調整每個數的大小,使得相鄰的兩個數的差小於一個給定的整數target,調整每個數的代價爲調整前後的差的絕對值,求調整代價之和最小是多少。
【注】:你可以假設數組中每個整數都是正整數,且小於等於100。
【題目鏈接】
www.lintcode.com/en/problem/minimum-adjustment-cost/
【題目解析】
這道題是揹包問題。
mac[i][j]表示前i個元素滿足要求且第i個元素爲j的最小cost。
初始化:mac[1][j] = Math.abs(A[0] - j),根據題意j在1到100之間。
對於所有在範圍內的k,當第i位元素取j時,取符合要求的第i-1位元素爲k的情況的最小值,其中abs(j-k)的值要小於target才能符合要求。
如果第i-1個數是j, 那麼第i-2個數只能在[lowerRange, UpperRange]之間,lowerRange=Math.max(0, j-target), upperRange=Math.min(99, j+target),
【參考答案】
www.jiuzhang.com/solutions/minimum-adjustment-cost/