您的位置:首页 > 其它

算法设计与应用基础系列2

2017-05-16 18:41 211 查看

152. Maximum Product Subarray

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
.

在数组中找到子阵(至少包含一个数字)具有最大。

例如,给定的数组[ 2,3 - 4 ],

的子阵[ 2,3 ]拥有最大= 6。

首先要先弄懂题目的意思就是根据数组得到一个最大的数,这是提供的数组得出一个最大结果
class Solution {

    int maxProduct(int A[], int n) {

    int frontProduct = 1;

    int backProduct = 1;

  int ans = INT_MIN;

  for (int i = 0; i < n; ++i) {

  frontProduct *= A[i];

  backProduct *= A[n - i - 1];

  ans = max(ans,max(frontProduct,backProduct));

     frontProduct = frontProduct == 0 ? 1 : frontProduct;

     backProduct = backProduct == 0 ? 1 : backProduct;

        }

        return ans;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: