152. Maximum Product Subarray

Description

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.

Solution

DP, time O(n), space O(1)

This is very similar to the " max cumulative sum subarray" problem. here you keep 2 values: the max cumulative product UP TO current element starting from SOMEWHERE in the past, and the minimum cumuliative product UP TO current element . it would be easier to see the DP structure if we store these 2 values for each index, like maxProduct[i],minProduct[i] .

At each new element, u could either add the new element to the existing product, or start fresh the product from current index (wipe out previous results), hence the 2 Math.max() lines.

If we see a negative number, the “candidate” for max should instead become the previous min product, because a bigger number multiplied by negative becomes smaller, hence the swap().

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int max = nums[0];
        // imax/imin stores the max/min product of
        // subarray that ends with the current number A[i]
        for (int i = 1, imax = nums[0], imin = nums[0]; i < nums.length; ++i) {
            if (nums[i] < 0) {
                int tmp = imax;
                imax = imin;
                imin = tmp;
            }
            // max/min product for the current number is 
            // either the current number itself
            // or the max/min by the previous number times the current one
            imax = Math.max(nums[i], nums[i] * imax);
            imin = Math.min(nums[i], nums[i] * imin);
            max = Math.max(max, imax);
        }
        
        return max;
    }
}

也可以這樣泥从,注意需要用tmp保存中間值:

class Solution {
    public int maxProduct(int[] nums) {
        int maxProduct = Integer.MIN_VALUE;
        
        for (int i = 0, imin = 1, imax = 1; i < nums.length; ++i) {
            int tmp = imax;
            imax = Math.max(nums[i], Math.max(imax * nums[i], imin * nums[i]));
            imin = Math.min(nums[i], Math.min(tmp * nums[i], imin * nums[i]));
            maxProduct = Math.max(maxProduct, Math.max(imax, imin));
        }
        
        return maxProduct;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末铡羡,一起剝皮案震驚了整個濱河市拼岳,隨后出現(xiàn)的幾起案子害捕,更是在濱河造成了極大的恐慌别厘,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阅悍,死亡現(xiàn)場離奇詭異屯断,居然都是意外死亡,警方通過查閱死者的電腦和手機瞒瘸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門坷备,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人情臭,你說我怎么就攤上這事省撑。” “怎么了俯在?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵竟秫,是天一觀的道長。 經(jīng)常有香客問我跷乐,道長肥败,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮馒稍,結(jié)果婚禮上皿哨,老公的妹妹穿的比我還像新娘。我一直安慰自己纽谒,他們只是感情好往史,可當我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著佛舱,像睡著了一般。 火紅的嫁衣襯著肌膚如雪挨决。 梳的紋絲不亂的頭發(fā)上请祖,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音脖祈,去河邊找鬼肆捕。 笑死,一個胖子當著我的面吹牛盖高,可吹牛的內(nèi)容都是我干的慎陵。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼喻奥,長吁一口氣:“原來是場噩夢啊……” “哼席纽!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起撞蚕,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤润梯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后甥厦,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纺铭,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年刀疙,在試婚紗的時候發(fā)現(xiàn)自己被綠了舶赔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡谦秧,死狀恐怖竟纳,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情油够,我是刑警寧澤扣草,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站沟突,受9級特大地震影響糜工,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜鬼悠,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一删性、第九天 我趴在偏房一處隱蔽的房頂上張望亏娜。 院中可真熱鬧,春花似錦蹬挺、人聲如沸维贺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽溯泣。三九已至,卻和暖如春榕茧,著一層夾襖步出監(jiān)牢的瞬間垃沦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工用押, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留肢簿,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓蜻拨,卻偏偏與公主長得像池充,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子缎讼,可洞房花燭夜當晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容