Skip to content

Instantly share code, notes, and snippets.

@loschtreality
Created March 20, 2017 17:06
Show Gist options
  • Save loschtreality/8a5f0101223f8c5c128cb46241495538 to your computer and use it in GitHub Desktop.
Save loschtreality/8a5f0101223f8c5c128cb46241495538 to your computer and use it in GitHub Desktop.
max double slice
const solution = (array) => {
const maxEndings = [0, 0, 0, 0, 0, 0, 0, 0]
const maxBeginnings = [0, 0, 0, 0, 0, 0, 0, 0]
for (let i = 1, len = array.length - 1; i < len; i++) {
maxEndings[i] = Math.max(maxEndings[i - 1] + array[i], 0)
}
for (let j = array.length - 2; j > 0; j--) {
maxBeginnings[j] = Math.max(maxBeginnings[j + 1] + array[j], 0)
}
let max = 0
for (let i = 1, len = array.length - 1; i < len; i++) {
const maxSum = maxEndings[i - 1] + maxBeginnings[i + 1]
max = Math.max(max, maxSum)
console.log(i, "INDEX")
console.log(maxEndings[i - 1], "end")
console.log(maxBeginnings[i + 1], "beg")
console.log(maxSum, "MAX SUM")
console.log("----------------------------")
}
console.log(maxEndings, "MAX ENDINGS")
console.log(maxBeginnings, "MAX BEGINNINGS")
return max
}
const array = [3, 2, 6, -1, 4, 5, -1, 2]
console.log(solution(array))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment