{"id":425,"date":"2020-03-26T05:38:00","date_gmt":"2020-03-26T05:38:00","guid":{"rendered":"https:\/\/danwritescode.com\/?p=425"},"modified":"2020-06-26T06:15:40","modified_gmt":"2020-06-26T06:15:40","slug":"max-slice-sum-codility-100-correct-javascript-solution","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/max-slice-sum-codility-100-correct-javascript-solution\/","title":{"rendered":"Max Slice Sum – Codility 100% Correct Javascript Solution"},"content":{"rendered":"\n
The Max Slice Sum was a fun brain challenge. <\/p>\n\n\n\n
I ended up finding the O(N) complexity solution after using the ol’ pen and paper trials.<\/p>\n\n\n\n
So, I iterated over the array. At each step I calculated the maximum sum ending at the current element by comparing the minimum sum allowed, the current element, and the maximum previous ending + the current element.
The max slice is the maximum between the previous max slice and the maximum ending at the current place. <\/p>\n\n\n\n
Solution in Javascript with O(N) complexity.<\/p>\n\n\n\n
function solution(A) {\n let minSum = 0-2147483648;\n let maxSlice = minSum\n let maxEnding = 0; \n for (let i=0; i<A.length; i++){\n\n maxEnding = Math.max(minSum, maxEnding+A[i], A[i])\n\n maxSlice = Math.max(maxEnding, maxSlice)\n\n } \n if (maxSlice > 2147483647) {\n maxSlice = 2147483647\n }\n return maxSlice\n \n}<\/code><\/pre>\n\n\n\n