152. Maximum Product Subarray

xiaoxiao2021-02-28  72

题目:

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.

大概就是找相邻的最大公共乘积吧 和最大子段和不一样,因为这个乘一个负数可能让人绝望,但是再乘一个,就可以起死回生,然后我就惊了,不知道咋整

感谢网上的大神们的支持

还是得用动态规划?

借鉴网上大神们的想法

如下

long maxProduct(int* nums, int numsSize)  {         if (numsSize == 0)              return 0;                  int max = 1, min= 1,result=nums[0];         for (int t = 0; t < numsSize; t++)          {             int old = maxnum (max, 1);             if (nums[t] > 0)             {                 max = old * nums[t];                 min *= nums[t];             }             else              {                 max = min * nums[t];                 min = old * nums[t];             }             result = maxnum (result, max);         }             return result;      } int maxnum(int a,int b) {     if(a>b)         return a;     else return b; }

大概意思就是 如果是正数,就按着老步子走,若是负数

Max是最大,min是最小,old是目前最大的,result 代表的是最终的

转载请注明原文地址: https://www.6miu.com/read-50870.html

最新回复(0)