[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
}

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10177238.html