LeetCode 152: Maximum Product Subarray

Maximum Product Subarray

  Total Accepted: 16617  Total Submissions: 96901

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.

[分析]

Besides keeping track of the largest product, we also need to keep track of the smallest product.

记录当前最大, 最小值. 因为遇到负数时, 与最小值的product可能成为最大值.

[注意事项]
注意0值的处理.

[CODE]


[java]  view plain  copy
  1. public class Solution {  
  2.     public int maxProduct(int[] A) {  
  3.         if(A==null || A.length<1return 0;  
  4.         if(A.length < 2return A[0];  
  5.   
  6.         int global = A[0];  
  7.         int max = A[0], min = A[0];  
  8.         for(int i=1; i<A.length; i++) {  
  9.             int a = max*A[i];  
  10.             int b = min*A[i];  
  11.               
  12.             max = Math.max(A[i], Math.max(a, b));  
  13.             min = Math.min(A[i], Math.min(a, b));  
  14.             global = Math.max(max, global);  
  15.         }  
  16.           
  17.         return global;  
  18.     }  
  19. }  



最大连续和数组:

  1. package secondCHA;  
  2.   
  3. public class maxSUM4 {  
  4.     static int MaxSubSequence( int A[])    
  5.     {    
  6.         int N=A.length;  
  7.         int ThisSum,MaxSum,j;    
  8.         ThisSum = MaxSum =0;    
  9.         for(j = 0;j < N;j++)    
  10.         {    
  11.             ThisSum += A[j];    
  12.                 
  13.             if(ThisSum > MaxSum)    
  14.                 MaxSum = ThisSum;    
  15.             else if(ThisSum < 0)    
  16.                 ThisSum = 0;     
  17.         }    
  18.         return MaxSum;     
  19.     }     
  20.     public static void main(String[] args) {  
  21.         // TODO Auto-generated method stub  
  22.           int[] a={4,-3,5,-2,-1,2,6,-2};  
  23.           System.out.println(MaxSubSequence(a));  
  24.     }  
  25.   
  26. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值