链接:
https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484?tpId=13&tqId=11183&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
描述:
示例:
代码:
方法一:
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array) {
int ret = array[0];
int dp[array.size()];
dp[0] = ret;
for(int i = 1;i<array.size();i++)
{
dp[i] = max(dp[i-1]+array[i],array[i]);
ret = dp[i]>ret?dp[i]:ret;
}
return ret;
}
};
定义一个数组用以记录
遍历到某个节点a时,此时前面的最大和是?
即:0,a 之间最大的所求为
方法二:
因为遍历到某个节点时,这个节点值只和前面一个节点有关
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> array)
{
int ret = array[0];
int a = ret;
for(int i = 1;i<array.size();i++)
{
a = max(array[i]+a,array[i]);
ret = ret>a?ret:a;
}
return ret;
}
};