Created
November 10, 2023 15:22
-
-
Save Git-I985/2a395515b335876c01a9caf13c889b91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function maxSumOfTwoRangesIn(arr) { | |
const ranges = [[]]; | |
for (let i = 0; i < arr.length; i++) { | |
const last = ranges.length - 1; | |
for (let j = 0; j <= last; j++) { | |
// ranges.push(ranges[j].concat(i)) | |
ranges.push([...ranges[j], i]); | |
} | |
} | |
let maxRangesSum; | |
for (let i = 0; i < ranges.length; i++) { | |
for (let j = i + 1; j < ranges.length; j++) { | |
if (ranges[j][0] > ranges[i].at(-1)) { | |
const a = arr.slice(ranges[i][0], ranges[i].at(-1) + 1) | |
const b = arr.slice(ranges[j][0], ranges[j].at(-1) + 1) | |
let s = 0; | |
for (let i = 0; i < Math.max(a.length, b.length); i++) { | |
s += (a[i] || 0) + (b[i] || 0) | |
} | |
if (!maxRangesSum || s > maxRangesSum) { | |
maxRangesSum = s | |
} | |
} | |
} | |
} | |
return maxRangesSum | |
} | |
console.log(maxSumOfTwoRangesIn([-5,9,-5,10,20])) | |
console.log(maxSumOfTwoRangesIn([1,2,3,4,5,6])) | |
console.log(maxSumOfTwoRangesIn([-1,-2,-3,-4,-5,-6])) | |
console.log(maxSumOfTwoRangesIn([1000,-100,-200,2000,-400,500,-600])) | |
console.time('et') | |
console.log(maxSumOfTwoRangesIn([-500,1000,-100,-2000,500,500,500,-5000,2000,-100,-200,3000,-400,500,-600])) | |
console.timeEnd('et') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment