152. Maximum Product Subarray
来源:互联网 发布:金牌网吧奖励软件 编辑:程序博客网 时间:2024/06/14 00:10
Description:
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
.
Solution:
int maxProduct(int A[], int n) { // store the result that is the max we have found so far int r = A[0]; // imax/imin stores the max/min product of // subarray that ends with the current number A[i] for (int i = 1, imax = r, imin = r; i < n; i++) { // multiplied by a negative makes big number smaller, small number bigger // so we redefine the extremums by swapping them if (A[i] < 0) swap(imax, imin); // max/min product for the current number is either the current number itself // or the max/min by the previous number times the current one imax = max(A[i], imax * A[i]); imin = min(A[i], imin * A[i]); // the newly computed max value is a candidate for our global result r = max(r, imax); } return r;}
class Solution {public: 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; }};
Summary:
自己写的时候花太多时间使用各种条件逻辑在负数与0的处理上了,没有抓住问题的本质。学习了大佬们的代码和算法,收获颇多。
路漫漫其修远兮,吾将上下而求索。
阅读全文
0 0
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- 152. Maximum Product Subarray
- Python入门(简介、安装)
- NOIP2014 飞扬的小鸟
- VirtualBox安装使用
- 芯海钩沉 | 英特尔4004:我最贵,但也最慢
- 泛型
- 152. Maximum Product Subarray
- python numpy库详解
- ASP.NET--网站配置、发布与部署
- 1.TCL/TK脚本学习——入门基础
- 九度OJ——1008最短路径问题
- 2.TCL脚本学习——Tk入门基础
- C
- 牛客网错题总结集(二)
- 3.TCL脚本学习——expect