题目:
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
.
题意:
题目中给出一个(至少包含一个元素)整形数组,求一个子数组(元素连续),使得其元素之积最大。
最直接了当的方法,当然是暴力穷举,但是其O(n^2)是无法通过LeetCode的OJ的。
以下给出了本题的解决方法,O(n)时间复杂度,C++实现。
1 class Solution {
2 public:
3 int maxProduct(int A[], int n) {
4 int nMaxPro = A[0];
5 int max_tmp = A[0];
6 int min_tmp = A[0];
7
8 for(int i = 1; i
9 int a = A[i] * max_tmp;
10 int b = A[i] * min_tmp;
11
12 max_tmp = (( a > b ? a : b ) > A[i]) ? ( a > b ? a : b ) : A[i];
13 min_tmp = (( a a : b ) : A[i];
14
15 nMaxPro = (nMaxPro > max_tmp) ? nMaxPro : max_tmp;
16 }
17
18 return nMaxPro;
19 }
20 };
运行结果:
希望各位看官不吝赐教,小弟感谢~!