题目:乘积最大子序列

找出一个序列中乘积最大的连续子序列(至少包含一个数)。

您在真实的面试中是否遇到过这个题?

Yes





样例

比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。

标签 Expand   



相关题目 Expand 

解题思路
 简单动态规划:

•用数组positive_max[i]维护原始数组前i个数的子数组乘积中正数的最大值
•用数组negative_min[i]维护原始数组前i个数的子数组乘积中负数的最小值

状态转移方程为:
if A[x] > 0:
  positive_max[x] = max(positive_max[x - 1] * A[x], A[x])
  negative_min[x] = negative_min[x - 1] * A[x]
elif A[x] < 0:
  positive_max[x] = negative_min[x - 1] * A[x]
  negative_min[x] = min(positive_max[x - 1] * A[x], A[x])



public class Solution {
    /**
     * @param nums: an array of integers
     * @return: an integer
     */
    public int maxProduct(int[] nums) {
        // write your code here
         int posmax = nums[0];
         int posmin = nums[0];
         int resmax = nums[0];
         for(int i=1;i<nums.length;i++){
              int a = posmax*nums[i];
              int b = posmin*nums[i];
              posmax = Math.max(Math.max(a, b), nums[i]);
              posmin = Math.min(Math.min(a, b), nums[i]);
              resmax = Math.max(resmax, posmax);
         }
         return resmax;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值