Algorithm 如何动态求解顺序拆分

Algorithm 如何动态求解顺序拆分,algorithm,Algorithm,数组arr中有许多权重。 arr=[1,5,3,2,4],arr中的每个值都包含权重。 n=2,分割时必须有2个块重量和顺序不能因分割而中断 Combination 1: block 0: [1] max: 1 block 1: [5,3,2,4] max: 5 ---------------------------- sum of max from block 0 and 1 is 6 Combination 2: block 0: [1,5] max: 5 b

数组arr中有许多权重。 arr=[1,5,3,2,4],arr中的每个值都包含权重。 n=2,分割时必须有2个块重量和顺序不能因分割而中断

Combination 1: 
block 0: [1]        max: 1
block 1: [5,3,2,4]  max: 5
----------------------------
sum of max from block 0 and 1 is 6

Combination 2: 
block 0: [1,5]      max: 5
block 1: [3,2,4]    max: 4
----------------------------
sum of max from block 0 and 1 is 9

Combination 3: 
block 0: [1,5,3]    max: 5
block 1: [2,4]      max: 4
----------------------------
sum of max from block 0 and 1 is 9

Combination 4: 
block 0: [1,5,3, 2] max: 5
block 1: [4]        max: 4
----------------------------
sum of max from block 0 and 1 is 9

So here answer is 6 from Combination 1

有些问题最难的部分就是把它们说清楚。如果你能做到这一点,代码实际上是自己写的

我认为问题是这样的:找到一个函数(f)的最小值,该函数应用于数组的每个索引(f(数组,索引)),其中f是两个子数组的最大值之和,这两个子数组是通过在给定索引处拆分输入数组形成的

函数f(数组、索引){
设left=array.slice(0,索引)
设right=array.slice(索引)
返回Math.max(…左)+Math.max(…右)
}
让数组=[1,5,3,2,4]
设smallestMax=无穷大

对于(设i=1;i@Danh有一个简单的O(N^2)解决方案,但是线性时间也可以,不需要太多的工作,如果你有足够的数据,这将产生巨大的差异。Dan在JS中完成了他的工作,所以我会尝试做同样的工作。这些样式的for循环有点生疏,所以它们可能会被关闭一次,但JS控制台中的快速测试给了我6次,正如预期的那样(在修复了复制/粘贴错误后)

想法是通过从左到右查找每个索引的最大值(左侧)。然后从右到左查找每个索引的最大值(右侧)。然后我们查看左侧和右侧以获得值。基本上是一种动态规划

let array = [1, 5, 3, 2, 4]
let maxLeft = {}
let maxRight = {}
let max,newMax;

for (let i=0; i<array.length; i++) {
  if (i === 0) {
    maxLeft[i] = array[i]
  } else {
    maxLeft[i] = array[i] < maxLeft[i-1] ? maxLeft[i-1] : array[i]
  }
}

for (let i=array.length - 1; i >= 0; i--) {
  if (i === array.length - 1) {
    maxRight[i] = array[i]
  } else {
    maxRight[i] = array[i] < maxRight[i+1] ? maxRight[i+1] : array[i]
  }
}

for (let i=0; i<array.length; i++) {
  newMax = maxLeft[i] + maxRight[i + 1]
  if (i === 0) {
    max = newMax 
  } else {
    maxLeft[i] = newMax < maxLeft[i-1] ? max : newMax 
  }
}
console.log(max)
let数组=[1,5,3,2,4]
设maxLeft={}
设maxRight={}
让马克斯,新马克斯;
for(设i=0;i=0;i--){
if(i==array.length-1){
maxRight[i]=数组[i]
}否则{
maxRight[i]=数组[i]对于(让i=0;我很好,非常干净,虽然有一个线性时间解决方案,但它有点凌乱。