@H_301_5@最差的方法给定一整数序列A1,A2,…,An(可能有负数),求A1到An的一个自序列,使得Ai到Aj的和最大。例如:整数序列-2,11,-4,13,-5,2,-5,-3,12,-9的最大子序列为21(从A2到A9)
```
var a = [-2,11,-4,13,-5,2,-3,12,-9]
var b = new Set()
for(let n in a){
let nm = [];
for(let m = n;m<a.length;m++){
nm.push(a[m])
}
add(...nm)
}
function add(...nums){
nums.reduce((x,y)=>{
b.add(x+y);
return x+y;
})
}
Math.max(...b)
优化
``` var a = [-2,-9] var b = new Set() for(let n in a){ a.reduce((x,y)=>{ b.add(x+y); return x+y; }) a.shift() } Math.max(...b)
ES6
```
var a = [-2,-9]
var b = new Set()
new class res{
constructor(){
a.reduce((x,y)=>{
b.add(x+y);
return x+y;
})
a.shift()
if(a.length) new res()
}
}
Math.max(...b)
最优-动态规划
var a = [-2,-9]
function method(data){ var max = 0; var m = data.length; var sum = 0; for(var i=0;i<m;i++){ sum+=data[i]; if(sum>max){ max=sum; }else if(sum<0){ sum = 0; } } return max;
}
method(a)