Maximum Subarray
2014-04-15 12:22
288 查看
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.
class Solution {
public:
int maxSubArray(int A[], int n)
{
int sum = 0;
int maxV = INT_MIN;
for (int i = 0; i < n; i++)
{
maxV = maxV > A[i] ? maxV : A[i];
sum += A[i];
if (sum > 0)
maxV = max( maxV, sum);
else
sum = 0;
}
return maxV;
}
};
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.
class Solution {
public:
int maxSubArray(int A[], int n)
{
int sum = 0;
int maxV = INT_MIN;
for (int i = 0; i < n; i++)
{
maxV = maxV > A[i] ? maxV : A[i];
sum += A[i];
if (sum > 0)
maxV = max( maxV, sum);
else
sum = 0;
}
return maxV;
}
};
相关文章推荐
- 浅析grep 查找文件内容实用命令
- 哈夫曼树
- 备忘录
- POJ 3304 Segments(线段直线相交)
- 不怕神一样的对手就怕猪一样的队友
- 不怕神一样的对手就怕猪一样的队友
- POSIX-Centos查看rpm包安装位置及相关信息
- 哈夫曼编码
- PHP把金额数字转换成大写形式
- deque(双端队列)
- -3+1
- HDU 1846 Brave Game(巴什博弈)
- Rose与PowerDesigner:两款建模工具的对比
- Delphi Excel 操作大全
- android ListView详解
- 关于button的小问题
- try...finally的妙用
- XML DOM加载函数
- 插入排序
- JQuery 【ajax上传文件】