191 乘积最大子数组

本文介绍了一种算法,用于在给定整数数组中寻找乘积最大的非空连续子数组。方法利用了0的特性,以及处理负数乘积的策略,通过C++代码实现Solution类来求解。
摘要由CSDN通过智能技术生成

题目描述

找出一个整数数组nums中乘积最大的非空连续子数组(至少包含一个数)

思路

0与任何数的积都是0,因此用0对数组进行切片。两个负数相乘,结果为正数,因此,对于一个连续的不含0的数组切片,只需要计算出整个切片的乘积tempResult,以及第一个负数出现前的乘积valueBeforeBegin,最后一个负数出现后的数的乘积valueAfterEnd。如果tempResult大于零,则取所有切片中最大的为最终结果,否则,分别结算tempResult/valueBeforeBegin和tempResult/valueAfterEnd的值,取其中最大的,即为此切片中最大的。

C++代码

class Solution {
public:
    /**
     * @param nums: An array of integers
     * @return: An integer
     */
    int maxProduct(vector<int> &nums) {
        // write your code here
        if (nums.size() == 1 && nums[0] < 0) {
            return nums[0];
        }

        int maxValue = 1;
        int tempResult = 1;

        int begin = -1;

        int valueBeforeBegin = 1;
        int valueAfterEnd = 1;

        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == 0 || i == nums.size() - 1) {
                if (nums[i] != 0) {
                    tempResult *= nums[i];
                    if (nums[i] < 0) {
                        valueAfterEnd = nums[i];
                    } else {
                        valueAfterEnd *= nums[i];
                    }
                }

                if (tempResult > 0) {
                    maxValue = std::max(tempResult, maxValue);
                } else {
                    maxValue = std::max(tempResult / valueBeforeBegin, maxValue);
                    maxValue = std::max(maxValue, tempResult / valueAfterEnd);
                }

                tempResult = 1;
                valueBeforeBegin = 1;
                valueAfterEnd = 1;
                begin = -1;
            } else {
                tempResult *= nums[i];
                if (begin == -1) {
                    valueBeforeBegin *= nums[i];
                }

                if (nums[i] < 0) {
                    if (begin == -1) {
                        begin = i;
                    }

                    valueAfterEnd = nums[i];
                } else {
                    valueAfterEnd *= nums[i];
                }
            }
        }

        return maxValue;
    }
};

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值