Maximum sub-array product algorithm and sub-array product Algorithm
Returns an array a and returns the product of the maximum subarray.
Algorithm idea: use dynamic sequence planning. Use maxValue (n) to represent the maximum sub-array product from 0 to n, and minValue (n) to represent the minimum sub-array product from 0 to n.
The state transition equation is:
MinValue (n) = min {minValue (n-1) * a [n], maxValue (n-1) * a [n], a [n]}
MaxValue (n) = max {minValue (n-1) * a [n], maxValue (n-1) * a [n], a [n]}
The maximum value is updated when the product of the maximum sub-array is obtained.
The Code is as follows:
class Solution{public: int maxProduct(vector<int>& nums) { int minValue = 1, maxValue = 1, result = numeric_limits<int>::min(); int len = nums.size(); for (int i = 0; i < len; i++) { int tempMin = min(maxValue * nums[i], min(minValue * nums[i], nums[i])); int tempMax = max(maxValue * nums[i], max(minValue * nums[i], nums[i])); minValue = tempMin; maxValue = tempMax; result = max(result, maxValue); } return result; }};
Taking array [2, 3,-2, 4] as an example, the output result is 6.
Verification Code:
#include <iostream>#include <algorithm>#include <vector>#include <limits>using namespace std;int main(){ int a[4] = {2, 3, -2, 4}; vector<int> nums(a, a + 4); Solution solver; int res = solver.maxProduct(nums); cout << res << endl; return 0;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.