题目描述
思路分析
我的想法是 先求出所有可能的连续数组和,记录当前数组和所对应的数组首尾位置,
使用map进行记录,之后将每个数组和对应的数组首尾位置进行比较,从而求出满足题目要求的最大值
代码解析
let input1 = [-1, 0, 4, -3, 6, 5, -6, 5, -7, -3], input2 = "bd", res = [], count = 0;
let m = new Map(), arr = [], cache = [], value = [], max = 0, maxValue = 0;
for (let i = 0; i < input1.length; i++) {
let sum = input1[i];
for (let j = i; j < input1.length; j++) {
if (i != j) {
sum += input1[j];
}
const c = sum;
m.set(c, m.has(c) ? m.get(c) + 1 : 1);
if (cache.indexOf(sum) != -1) {
arr.map(item => {
if (item[0] == sum) value = item[1]
})
value.push([i, j])
} else {
value = []
value.push([i, j])
arr.push([sum, value])
cache.push(sum)
}
}
}
for (let i = 0; i < arr.length; i++) {
let cc = arr[i][1]
console.log('arr[i]=>', cc);
if (cc.length > max) {
var list = Array(cc.length).fill(-1)
func(cc, 0)
max = Math.max(max, maxValue);
maxValue = 0;
console.log('list=>', list);
}
}
function func (item, index) {
if (list[index] != -1) return list[index];
let count = 0, max = 0;
for (let i = index; i < item.length; i++) {
let start = item[index][1];
count++;
if (start < item[i][0]) {
for (let j = i; j < item.length; j++) {
if (start < item[j][0]) {
start = item[j][1];
count++
}
}
}
max = Math.max(count, max)
count = 0
}
console.log('max=>', max);
let nextIndex = index + 1;
while (nextIndex < item.length) {
let rres = func(item, nextIndex)
if (item[index][1] < item[nextIndex][0]) {
max = Math.max(max, rres + 1);
}
nextIndex++;
}
list[index] = max
maxValue = Math.max(max, maxValue);
return max;
}
console.log('max=>', max);
后话
只是记录,正在找工作中,各位老板缺前端的可以私信,会vue,react,ts,js,22届本科毕业,一年工作经验