(微软100题)3.求子数组的最大和
2014-02-14 17:22
162 查看
#include <iostream> using namespace std; /*3.求子数组的最大和 题目: 输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。要求时间复杂度为O(n)。 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2, 因此输出为该子数组的和18。 ANSWER: A traditional greedy approach. Keep current sum, slide from left to right, when sum < 0, reset sum to 0. */ int maxSubarray(int a[], int size) { if (size<=0) cout<<("error array size"); int sum = 0; int max = - (1 << 31); int cur = 0; while (cur < size) { sum += a[cur++]; if (sum > max) { max = sum; } else if (sum < 0) { sum = 0; } } return max; } void main() { int test[8] = {1,-2,3,10,-4,7,2,-5}; cout<<maxSubarray(test,8)<<endl; system("pause"); }
相关文章推荐
- Sql server 浅谈用户定义表类型
- 《汇编语言·王爽》读书笔记
- 从头写一个rtsp服务器
- Python 文件夹和文件操作汇总
- SQL 优化原则
- VMware P2V物理机虚拟化流程
- Android高效加载大图、多图解决方案,有效避免程序OOM
- getAngle, getNewPoint
- ORACLE用户建表:ORA-01950: no privileges on tablespace 解决
- c++获取系统当前时间
- ORA-01652(永久表空间临时段不能扩展情况分析)
- 支持Android4.0以下webp的使用
- ARM软件优化,从1s到10ms
- js通过点击一个按钮跳转到一个查询页面--window.showModalDialog
- IMS 相关名词解释
- 露眼看App--怎样做一款旅游类的App ?
- 网页图标使用字体文件来定义
- 谈谈如何学习Linux内核 (二) —— 站在系统的角度去学习
- 对于android手机2px的解决方案
- 读写者的四种优先调度方式