【LeetCode】152. Maximum Product Subarray
2016-03-28 14:57
344 查看
题目:
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.
提示:
这道题可以使用动态规划求解,但是由于是乘法运算,所以情况更加复杂。联想乘法运算的性质:两个负数相乘得到一个正数,也就是说我们在计算过程中,如果产生了一个很大的负数,之后又遇到了一个负数,那么其乘积就会变成正数,进而可能成为潜在的答案。因此,我们创建两个变量,分别记录运算过程中的最大值和最小值。另外,当遇到负数时,把这两个变量进行交换(因为那个最小值乘以负数之后就会成为最大值)。具体看下列代码:代码:
class Solution { public: int maxProduct(vector<int>& nums) { if (nums.empty()) { return 0; } int res = nums[0]; for (int i = 1, imax = res, imin = res; i < nums.size(); ++i) { if (nums[i] < 0) { swap(imax, imin); } // 幸运的是,这样的做法对数值0也同样有效 imax = max(nums[i], imax * nums[i]); imin = min(nums[i], imin * nums[i]); res = max(res, imax); } return res; } };
相关文章推荐
- 在内核窥视用户态
- cordova 设置-all_load错误
- SQL 通配符使用
- adb logcat 查看日志
- Subscriber class xxx.xxx.xxx and its super classes have no public methods with the@Subscribe annotat
- python数据结构——层次遍历的两种方法
- MVC学习系列——HtmlHelper扩展
- php中include_once,require_once,和include,require的使用场景和区别。
- 获取Android设备唯一标识码
- 如何做一个健全的分页功能(包括能够查询以后自动显示分页功能,基于MVC以及SSH框架)
- linux上部署Django项目(Apache+mod_wsgi+django)
- postgres压测工具pgbench
- Java中Vector与ArrayList,HashMap与HashTable
- 欢迎使用CSDN-markdown编辑器
- j2ee Servlet、Filter、Listener
- 电梯调度算法总结
- Mybatis框架_part1
- view视图--display中echo出ob_get_contents的缓冲内容--(实现,拼接好文件--导入文件)
- 内核和进程通信方式
- 论坛收集