题目相关
【题目解读】
获取数组中最大子串,并返回该最大值
【题目】原题链接
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
【难度】Easy
Solution
自己采用的方法,求得max、min,然后根据max、min的位置进行计算,不过自己想到的几个测试用例都未能跑通,还需改进代码:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
if(len == 1) return nums[0];
int min = 0;
int max = 0;
for(int i = 1; i < len; i++)
{
if(nums[min] > nums[i]) min = i;
if(nums[max] < nums[i]) max = i;
}
int ret = 0;
int ret_left = 0;
int ret_right = 0;//如果max在中间,需要进行比较
if(min < max)
{
for(int i = min+1; i <= max; i ++)
ret += nums[i];
}else{
for(int i = 0;i < min; i ++)
if(i < max)
ret_left += nums[i];
else
ret_right += nums[i];
}
if(ret_left < 0)
ret = ret_right;
else
ret =ret_left + ret_right;
return ret;