week14- Dynamic Programming-NO.152. Maximum Product Subarray

xiaoxiao2021-02-27  243

题目 Total Accepted: 97998Total Submissions: 388053Difficulty: MediumContributor: LeetCode

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.

https://leetcode.com/problems/maximum-product-subarray/#/description

思路

题目给定一个整数数组,希望求得其中乘积最大的连续子数组。 使用动态规划,遍历以第i个数开头和第j个数结尾的子数组的乘积,取其中的最大值。

源程序

class Solution { public: int maxProduct(vector<int>& nums) { int length = nums.size(); if(length == 0) return 0; if(length == 1) return nums[0]; int max, min; int a,b,r = nums[0]; for(int i = 0;i < length;i ++){ max = nums[i]; min = nums[i]; for(int j = i + 1;j < length;j ++){ a = nums[j] * max; b = nums[j] * min; min = a < b ? a : b; max = a > b ? a : b; r = max > r ? max : r; } r = nums[i] > r ? nums[i] : r; } return r; } };
转载请注明原文地址: https://www.6miu.com/read-8904.html

最新回复(0)