leetcode 053 —— Maximum Subarray
2015-07-23 19:28
381 查看
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
思路:贪心算法,如果当前sum+num[i]<0,重置sum为0
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int sum = 0;
int maxSum = INT_MIN;
for (int i = 0; i < n; i++){
sum += nums[i];
if (sum>maxSum)
maxSum = sum;
if (sum < 0)
sum = 0;
}
return maxSum;
}
};
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.
思路:贪心算法,如果当前sum+num[i]<0,重置sum为0
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
int sum = 0;
int maxSum = INT_MIN;
for (int i = 0; i < n; i++){
sum += nums[i];
if (sum>maxSum)
maxSum = sum;
if (sum < 0)
sum = 0;
}
return maxSum;
}
};
相关文章推荐
- HDOJ 1718 Rank(结构体)
- MatLab7安装方法
- [iOS Keychain本地长期键值存储]
- Python的捕虫笔记
- 黑马程序员——第三篇_知识点整理
- Python的捕虫笔记
- leetcode:Palindrome Linked List
- 那些年,我们读过的python!
- HDU 4745——Two Rabbits
- NGUI3.9.0 Scroll View
- Android开源计划-一周开发app
- hdu 1087 Super Jumping! Jumping! Jumping!(最长上升子序列&dp)
- C++中的关键字explict
- 快速排序优化通过中位数优化
- 【java】利用set集合特性去重
- bzoj-4003 城池攻占
- BZOJ 2588 Count on a tree (COT) 是持久的段树
- 社会保障系列1《介绍》
- Linux远程登录Windows桌面
- 少年 DXH