1. 程式人生 > >[Algorithms] Solve Complex Problems in JavaScript with Dynamic Programming

[Algorithms] Solve Complex Problems in JavaScript with Dynamic Programming

Every dynamic programming algorithm starts with a grid. It entails solving subproblems and builds up to solving the big problem. Let’s break down a problem and solve it in pieces using dynamic programming with JavaScript.

 

/**
 * 給一個浮點數序列,取最大乘積連續子串的值,例如 -2.5,4,0,3,0.5,8,-1,則取出的最大乘積連續子串為3,0.5,8。也就是說,上述陣列中,3 0.5 8這3個數的乘積30.58=12是最大的,而且是連續的
 * @param {*} a 
 
*/ function MaxProductSubstring (a) { let maxEnd = a[0] let maxRes = a[0] for (let i = 1; i < a.length; i++) { maxEnd = Math.max(maxEnd * a[i], a[i]) maxRes = Math.max(maxRes, maxEnd) } return maxRes }