原题如下所示:
连续子数组求和
给定一个整数数组,请找出一个连续子数组,使得该子数组的和最大。输出答案时,请分别返回第一个数字和最后一个数字的下标。(如果两个相同的答案,请返回其中任意一个)
给定 [-3, 1, 3, -3, 4]
, 返回[1,4]
.
1、一看到题目就觉得是动态规划的问题,可以定义一个和输入数组相等大小的数组sum,用来存放到当前位置为止的最大子数组和,然后求出该数组中最大值所在的位置就是输出的右侧的位置;
2、求左侧位置的时候,可以发现,最大的子数组的和一定是sum中,从第一个大于0的数开始的,所以从右侧往前查找到第一个小于0的数,其+1就是左侧的值。
具体的C++代码如下:
class Solution {
public:
/**
* @param A an integer array
* @return A list of integers includes the index of
* the first number and the index of the last number
*/
vector<int> continuousSubarraySum(vector<int>& A) {
// Write your code here
vector<int> res;
if(A.size()==0)
{
return res;
}
else
{
int len=A.size();
vector<int> sum(len,0);
sum[0]=A[0];
int left,right;
int i;
for(i=1;i<len;i++)
{
sum[i]=max(A[i],A[i]+sum[i-1]);
}
int max=sum[0];
for(i=1;i<len;i++)
{
if(sum[i]>max)
{
max=sum[i];
right=i;
}
}
if(sum[right]==A[right])
{
res.push_back(right);
res.push_back(right);
}
else
{
for (i = right; i>=0; i--)
{
if (sum[i] <0)
{
left = i+1;
break;
}
}
res.push_back(left);
res.push_back(right);
}
return res;
}
}
};