1. 程式人生 > >找出數組中的連續最大乘積

找出數組中的連續最大乘積

int 子序列 clas length 子數組 示例 一個 連續 乘積最大

給定一個整數數組 nums ,找出一個序列中乘積最大的連續子序列(該序列至少包含一個數)。

示例 1:

輸入: [2,3,-2,4]
輸出: 6
解釋: 子數組 [2,3] 有最大乘積 6。
示例 2:

輸入: [-2,0,-1]
輸出: 0
解釋: 結果不能為 2, 因為 [-2,-1] 不是子數組。

class Solution {
public int maxProduct(int[] nums) {
int fmax1, fmax2;
fmax2 = nums[0];
for(int i=0; i<=nums.length-1; i++){
fmax1 = nums[i];
for(int j=i; j<=nums.length-1; j++){

if(j > i){
fmax1 *= nums[j];
}
if(fmax2 < fmax1){
fmax2 = fmax1;
}
}
}
return fmax2;
}
}

找出數組中的連續最大乘積