[DP解题] 乘积最大子序列
原题链接:https://leetcode.com/problems/maximum-product-subarray/
[问题]
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
题目的意思是给定一个整形数组nums,要求在数组中找到连续的子序列使得子序列的乘积最大(子序列至少包含一个整数)
例如:给定数组 [2,3,-2,4],最大连续子序列乘积为6。因为最大的连续子序列 [2,3],其最大乘积为6。
[算法分析]
这道题最直接的方法就是用DP来做,而且要用两个dp变量,其中:
dpMax:代表nums数组中下标从[0...i]时的最大乘积
dpMin:代表nums数组中下标从[0...i]时的最小乘积
为什么呢?
初始时,当i=0时,即数组中的第一个元素:
dpMax=dpMin=answer=nums[0] (可能为0,正值,负值)
当i=1时:即数组中的第二个元素,这时要考虑几种情况,

本篇博客介绍如何使用动态规划(DP)解决LeetCode上的'最大乘积子序列'问题。通过分析不同情况,得出利用dpMax和dpMin记录最大值和最小值的策略,以求得连续子序列的最大乘积。例如,对于数组[-2, 3, -2, 4],最大乘积子序列为[2, 3],乘积为6。"
121681831,10823747,"Vue.js 条件渲染实践:v-if, v-else, v-else-if, v-show
最低0.47元/天 解锁文章
102

被折叠的 条评论
为什么被折叠?



