File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ``` text
2+ 题目: 在给定整数数组nums中,找出乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积;
3+ 输入: [2,3,-2,4]
4+ 输出: 6
5+ 解释: 子数组 [2,3] 有最大乘积 6
6+ 输入: [-2,0,-1]
7+ 输出: 0
8+ 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组
9+ 1.动态规划:
10+ [1]思路:
11+ (1)遍历数组时计算当前最大值,不断更新
12+ (2)令imax为当前最大值,则当前最大值为 imax = max(imax * nums[i], nums[i])
13+ (3)由于存在负数,那么会导致最大的变最小的,最小的变最大的;
14+ 因此还需要维护当前最小值imin,imin=min(imin * nums[i], nums[i])
15+ (4)当负数出现时则imax与imin进行交换再进行下一步计算;
16+ [2]实现:
17+ class Solution {
18+ public int maxProduct(int[] nums) {
19+ // 定义三个变量: 最大值,前i项乘积的最大值,前i项乘积的最小值
20+ int max = Integer.MIN_VALUE,imax =1,imin = 1;
21+ // 遍历数组
22+ for (int num : nums) {
23+ // 如果当前遍历值为负数,则前i项乘积的最大值变成最小值,前i项乘积的最小值变成最大值
24+ // 即交换前i项的最大值和前i项的最小值
25+ if(num < 0){
26+ int temp = imax;
27+ imax = imin;
28+ imin = temp;
29+ }
30+ // 前i项乘积的最大值
31+ imax = Math.max(imax*num,num);
32+ // 前i项乘积的最小值
33+ imin = Math.min(imin*num,num);
34+ // 前i项中乘积最大的子数组最大值
35+ max = Math.max(max,imax);
36+ }
37+ return max;
38+ }
39+ }
40+ [3]复杂度分析:
41+ (1)时间复杂度: O(n)
42+ (2)空间复杂度: O(1)
43+ ```
You can’t perform that action at this time.
0 commit comments