{"id":420,"date":"2020-03-30T05:05:00","date_gmt":"2020-03-30T05:05:00","guid":{"rendered":"https:\/\/danwritescode.com\/?p=420"},"modified":"2020-06-26T05:29:20","modified_gmt":"2020-06-26T05:29:20","slug":"max-profit-codility-100-correct-solution","status":"publish","type":"post","link":"https:\/\/danwritescode.com\/max-profit-codility-100-correct-solution\/","title":{"rendered":"Max Profit Codility – 100% Correct Solution"},"content":{"rendered":"\n
The Max Profit Codility challenge put me to a solid test in order to find a O(N) solution.<\/p>\n\n\n\n
In the end I found the following algorithm:<\/p>\n\n\n\n
I iterated the array of stock prices. At each point I calculated the maximum profit that could be obtained in point and the minimum price met until that point. Then I compared the maximum so far with the current maximum possible profit and kept the biggest one in the maxSoFar value.<\/p>\n\n\n\n
function solution(A) {\n let maxSoFar = maxEndingHere = 0;\n let minPrice = A[0]\n for (let i = 0; i < A.length; i++){\n maxEndingHere = Math.max(0, A[i]-minPrice)\n minPrice = Math.min(minPrice, A[i])\n maxSoFar = Math.max(maxEndingHere, maxSoFar)\n } \n return(maxSoFar)\n}<\/code><\/pre>\n\n\n\n