Algorithm 最大增重子序列

Algorithm 最大增重子序列,algorithm,dynamic-programming,Algorithm,Dynamic Programming,在这种情况下,如果我们按重量改变长度,即如果我们将每个元素的长度Ai改为Wi,则其长度为1 我们如何在O(NlogN)中实现它 比如说 对于8个元素的数组 Elements 1 2 3 4 1 2 3 4 Weights 10 20 30 40 15 15 15 50 最大重量是110磅 我在wikipedia上找到了LIS解决方案,但我无法修改它来解决这个问题。不过,我们使用f[I]表示序列以E[I]结尾时可以得到的最大值 因此,通常我们有for(inti=1;i这里是sw

在这种情况下,如果我们按重量改变长度,即如果我们将每个元素的长度Ai改为Wi,则其长度为1 我们如何在O(NlogN)中实现它

比如说 对于8个元素的数组

Elements 1  2  3  4  1  2  3  4
Weights  10 20 30 40 15 15 15 50 
最大重量是110磅


我在wikipedia上找到了LIS解决方案,但我无法修改它来解决这个问题。

不过,我们使用
f[I]
表示序列以
E[I]
结尾时可以得到的最大值


因此,通常我们有
for(inti=1;i这里是swift中的纯递归实现:

// input is Array of (a,w), where a is element and w is weight

func lisw(input: [(Int, Int)], index:Int = 0, largestA:Int? = nil)->Int{
       guard index < input.count else { return 0 }

       let (a,w) = input[index]

       if a <= largestA {
          return lisw(input: input, index: index + 1, largestA: largestA)
       }

       let without_me = lisw(input: input, index: index + 1, largestA: largestA == nil ? a : largestA)
       let with_me = lisw(input: input, index: index + 1, largestA: a) + w

       return max(without_me,with_me)
}
//输入是(a,w)的数组,其中a是元素,w是权重
func-lisw(输入:[(Int,Int)],索引:Int=0,largestA:Int?=nil)->Int{
保护索引如果a什么是dp[i]?您能告诉我段树中存储了什么吗?谢谢。@amahfouz dp(i)只是一个计算f[i]值的函数。在段树中,索引(或范围)是E的值,更新单个插槽的值,查询范围内的最大值,典型段树。感谢您的回复。使用testcases在HackerRank上解决此问题-www.HackerRank.com/challenges/subsequence-weighting