Codility: MaximumDoubleSliceSum Solution
Lesson 9 Maximum Slice ProblemApproach
Kadane algorithm
(X, Y, Z): X + 1, Z - 1, and skip Y
Maintain 2 kadane prefix, one for ending at (normal), one for starting at (reversed)
Implementation
1function solution(A) {2 const N = A.length3 const maxEndingAt = Array(N).fill(0)4 const maxStartingAt = Array(N).fill(0)56 for (let i = 1; i < N - 1; i++) {7 maxEndingAt[i] = Math.max(0, maxEndingAt[i - 1] + A[i])8 }9 for (let i = N - 2; i > 0; i--) {10 maxStartingAt[i] = Math.max(0, A[i] + maxStartingAt[i + 1])11 }1213 let max = -Infinity14 for (let i = 1; i < N - 1; i++) {15 max = Math.max(max, maxEndingAt[i - 1] + maxStartingAt[i + 1])16 }17 return max18}
Comments
Loading comments...
Tags
codility
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.