(卓越的人一大优点是:在不利与艰难的遭遇里百折不饶。——贝多芬)
const array = [1, -2, 2, 0, -5, 3, -2, 7, 1, -2, 10];
const getResult = (childList, resultList) => {
let len = resultList.length;
for (let i = 0; i < len; i++) {
if (resultList[i] > resultList[i + 1]) {
const temp = resultList[i];
const tempResult = [...childList[i]];
resultList[i] = resultList[i + 1];
resultList[i + 1] = temp;
childList[i] = childList[i + 1];
childList[i + 1] = tempResult;
}
if (i === len) {
i = -1;
len -= 1;
}
}
return {
childList, resultList };
}
(() => {
const list = [];
const resultList = [];
for (let i = 0; i < array.length; i++) {
let item = array[i];
list.push([item]);
const tempList = [item];
resultList.push(item);
for (let j = i + 1; j < array.length; j++) {
if (typeof array[j] === 'number') {
item += array[j];
tempList.push(array[j]);
const newTempList = [...tempList];
list.push(newTempList);
resultList.push(item);
}
}
}
const result = getResult(list, resultList);
console.log(result.childList[result.childList.length - 1], result.resultList[result.resultList.length - 1]);
})();
(() => {
let baseNumberIndex = -1;
let baseNumber = null;
let startIndex = -1;
let tempList = [];
const list = [];
const resultList = [];
for (let i = 1; i < array.length; i++) {
baseNumber += array[i];
tempList.push(array[i]);
list.push([...tempList]);
resultList.push(baseNumber);
if (i === 1 || i === array.length - 1) {
baseNumberIndex += 1;
baseNumber = array[baseNumberIndex];
tempList = [baseNumber];
list.push(tempList);
resultList.push(baseNumber);
startIndex += 1;
i = startIndex;
}
if (baseNumberIndex === array.length - 1) {
break;
}
}
const result = getResult(list, resultList);
console.log(result.childList[result.childList.length - 1], result.resultList[result.resultList.length - 1]);
})();