我在处理这个问题的memoization和自下而上的方法算法时遇到了麻烦:
假设您拥有xi
元素数组,-10000 < xi < 10000
,所有0 < i < N
。试图找到T元素的最大总和,T <0.05。 N使得它们排列在不同的子阵列中。我们不对每个子阵列中的第一个元素求和,并且我们也必须返回子阵列的数字K.
一个例子应该解释:
T=4,
array = 3 9 1 1 7 => (3 9) and (1 7) have maximum sum 16= 9 + 7 ,K = 2
T=4,
array = 3 9 6 3 7 => (3 9 6 3) have maximum sum 18 = 9 + 6 + 3 , K = 1
* T = 9,array = 14 11 18 1 1 16 12 18 0 0 11 18 9 5 14 =&gt;连续的子阵列是(14 11 18)(1 16 12 18)(11 18)K = 3和max_sum = 11 + 18 + 16 + 12 + 18 + 18 = 93 ** **对于T = 15阵列= 6 19 -29 15 9 -4 5 27 3 12 -10 5 -2 27 10 -2 11 23 -4 5 =&gt;连续的子阵列是(6 19)( - 29 15 9)(5 27 3 12)(-2 27 10)( - 2 11 23),K = 5,max_sum = 19 + 15 + 9 + 27 + 3 + 12 +27 + 10 + 11 + 23 = 156
这是我到目前为止所做的:
let f[i][j][0] denotes the maximal sum for the first i slots and using j slots, and the i-th slot is not used.
let f[i][j][1] denotes the maximal gain for the first i slots and using j slots , and the i-th slot is used.
显然,f[i][j][k]
可以确定f[i+1][j][k]
或f[i+1][j+1][k]
细节:
f[i+1][j+1][1]=max(f[i+1][j+1][1],f[i][j][0],f[i][j][1]+G[i+1]);
f[i+1][j][0]=max(f[i+1][j][0],f[i][j][0],f[i][j][1]);
答案 0 :(得分:0)
这是Haskell中的一个版本。函数'partitions'由Daniel Fischer编写,它以所有可能的方式对列表(或数组)进行分区。其余代码使用长度大于1的元素测试分区,其组合长度与T匹配,并返回具有最大总和的分区(根据请求汇总没有第一个数字)。
import Data.List (maximumBy)
import Data.Ord (comparing)
partitions [] = [[]]
partitions (x:xs) = [[x]:p | p <- partitions xs]
++ [(x:ys):yss | (ys:yss) <- partitions xs]
findMax t xs =
let toTest = filter (\z -> (sum $ map length z) == t)
$ map (\x -> filter (\y -> length y > 1) x)
$ partitions xs
result = maximumBy (comparing snd)
(zip toTest (map (\x -> sum $ map (sum . drop 1) x) toTest))
in putStrLn(
show result
++ " K = "
++ show (length $ fst result))
OUTPUT:
*Main> findMax 4 [3,9,1,1,7]
([[3,9],[1,7]],16) K = 2
*Main> findMax 4 [3,9,6,3,7]
([[3,9,6,3]],18) K = 1
*Main> findMax 9 [14,11,18,1,1,16,12,18,0,0,11,18,9,5,14]
([[14,11,18],[1,16,12,18],[11,18]],93) K = 3