leetcode152:乘積最大子序列

自己想的方法:
雙重for循環,外層控制開始的地方,內層控制從開始到數組最後
不斷替換最大值,最終得出結果,但是效率很低
代碼:

package com.leetCode.dp;

public class leet152 {
	public static void main(String[] args) {
		int[] arr = {0,2};
		System.out.println(maxProduct(arr));
	}
	public static int maxProduct(int[] nums) {
		int ans=Integer.MIN_VALUE;
		if(nums.length==0||nums==null) return 0;
		if(nums.length==1) return nums[0];
		int now=1;
		for(int i=0;i<nums.length;i++)
		{
			now=1;
			for(int j=i;j<nums.length;j++)
			{
				now=now*nums[j];
				if(now>ans) ans=now;
			}
		}
		return ans;
    }
}

題解方法:
同時存在最大值與最小值(負的最大值)
在這種情況下,如果遇到
每當遇到一個負數,最大值與最小值進行替換
然後:
最大值變爲Math.max(原來最大值這個數,這個數)
最小值變爲Math.min(最小值
這個數, 這個數);

max在原來最大值和最大值之間取
※代碼:

class Solution {
    public int maxProduct(int[] nums) {
        int max = Integer.MIN_VALUE, imax = 1, imin = 1;
        for(int i=0; i<nums.length; i++){
            if(nums[i] < 0){ 
              int tmp = imax;
              imax = imin;
              imin = tmp;
            }
            imax = Math.max(imax*nums[i], nums[i]);
            imin = Math.min(imin*nums[i], nums[i]);
            
            max = Math.max(max, imax);
        }
        return max;
    }
}


作者:guanpengchn
鏈接:https://leetcode-cn.com/problems/maximum-product-subarray/solution/hua-jie-suan-fa-152-cheng-ji-zui-da-zi-xu-lie-by-g/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章