1. 程式人生 > >【LeetCode & 劍指offer刷題】動態規劃與貪婪法題5:Maximum Product Subarray

【LeetCode & 劍指offer刷題】動態規劃與貪婪法題5:Maximum Product Subarray

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Maximum Product Subarray

Given an integer array  nums , find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input:
[2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

C++   /* 問題:求最大子陣列乘積 方法:動態規劃 兩個dp陣列,其中f[i]和g[i]分別表示包含nums[i](以nums[i]結尾)時的最大和最小子陣列乘積, 初始化時f[0]和g[0]都初始化為nums[0],其餘都初始化為0。   從陣列的第二個數字開始遍歷,此時的最大值和最小值只會在這三個數字之間產生,
即f[i-1]*nums[i],g[i-1]*nums[i],和nums[i]。 所以我們用三者中的最大值來更新f[i],用最小值來更新g[i],然後用f[i]來更新結果res即可 */ class Solution { public :     int maxProduct ( vector < int >& nums )     {         if ( nums . empty ()) return 0 ;                     int res = nums [ 0 ], n = nums . size ();         vector < int > f ( n ), g ( n ); //分配空間,初始化         f[0] = nums[0];         g[0] = nums[0];                 for ( int i = 1 ; i < n ; i ++) //從a[1]開始遍歷         {             f [i] = max(max(f[i - 1] * nums[i], g[i - 1] * nums[i]), nums[i]); //最大數更新             g [ i ] = min ( min ( f [ i - 1 ] * nums [ i ], g [ i - 1 ] * nums [ i ]), nums [ i ]); //最小數更新             res = max ( res , f [ i ]); //結果更新         }         return res ;     } };   /* 空間優化,用兩個變數代替陣列dp  */ class Solution { public :     int maxProduct ( vector < int >& nums )      {         if ( nums . empty ()) return 0 ;         int res = nums [ 0 ], mn = nums [ 0 ], mx = nums [ 0 ];         for ( int i = 1 ; i < nums . size (); ++ i )          {             int tmax = mx , tmin = mn ; //上一次的最小值和最大值             mx = max ( max ( nums [ i ], tmax * nums [ i ]), tmin * nums [ i ]);             mn = min ( min ( nums [ i ], tmax * nums [ i ]), tmin * nums [ i ]);             res = max ( res , mx );         }         return res ;     } };