53. Maximum Subarray
2016-05-12 13:14
441 查看
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题意:求数组中和最大的连续序列
思路:max(n) = max{ max(n-1), sum+a
}, 其中sum表示连续到n的非负片段和(即:若sum<0,则sum从0开始计数)。
For example, given the array
[−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray
[4,−1,2,1]has the largest sum =
6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题意:求数组中和最大的连续序列
思路:max(n) = max{ max(n-1), sum+a
}, 其中sum表示连续到n的非负片段和(即:若sum<0,则sum从0开始计数)。
class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.size() < 1) return 0; int maxNum = (numeric_limits<int>::min)(); int sum = 0; for (int i = 0; i < nums.size(); i++){ sum += nums[i]; if (sum > maxNum) maxNum = sum; if (sum < 0){ sum = 0; } } return maxNum; } };
相关文章推荐
- top命令
- LeetCode 029 Divide Two Integers
- 动态规划
- 图文详解Ubuntu下安装配置Mysql教程
- Linux进程描述符task_struct结构体详解--Linux进程的管理与调度(一)
- 一站式WPF--线程模型和Dispatcher
- Server-01 How to Find the Remote Desktop Port
- RxJava flatmap
- Android---activity的生命周期
- 【LeetCode】234. Palindrome Linked List
- VideoView 播放资源目录raw下的视频
- disable application 的notification
- 剑指offer题解【合并两个排序的链表】-java
- mybatis xml 中的特殊符转义字符号和模糊查询
- js导出excel
- python2.7 模块全局__metaclass__
- 轻松吃掉 高血压、高血脂、高血糖
- 正则表达式 贪婪模式和非贪婪模式
- 如何测试一个杯子
- 小代码 找出重复过半的数 (特性一维数组)