首页 > 试题广场 >

连续子数组的最大和(二)

[编程题]连续子数组的最大和(二)
  • 热度指数:46287 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组,找到一个具有最大和的连续子数组。
1.子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组
2.如果存在多个最大和的连续子数组,那么返回其中长度最长的,该题数据保证这个最长的只存在一个
3.该题定义的子数组的最小长度为1,不存在为空的子数组,即不存在[]是某个数组的子数组
4.返回的数组不计入空间复杂度计算

数据范围:



要求:时间复杂度,空间复杂度
进阶:时间复杂度,空间复杂度


示例1

输入

[1,-2,3,10,-4,7,2,-5]

输出

[3,10,-4,7,2]

说明

经分析可知,输入数组的子数组[3,10,-4,7,2]可以求得最大和为18,故返回[3,10,-4,7,2]   
示例2

输入

[1]

输出

[1]
示例3

输入

[1,2,-3,4,-1,1,-3,2]

输出

[1,2,-3,4,-1,1]

说明

经分析可知,最大子数组的和为4,有[4],[4,-1,1],[1,2,-3,4],[1,2,-3,4,-1,1],故返回其中长度最长的[1,2,-3,4,-1,1]   
示例4

输入

[-2,-1]

输出

[-1]

说明

子数组最小长度为1,故返回[-1]   
在连续子数组的基础上,记录起始点和个数,注意因为要求最长,所以在最大值处要加上判断等于
int* FindGreatestSumOfSubArray(int* array, int arrayLen, int* returnSize ) 
{
    // write code here
    if(array == NULL || arrayLen == 0)
        return NULL;
    int sum = array[0],max_sum = sum,start = 0,cnt=1,j=0;
    int tmp_cnt = 1;
    for(int i =1;i<arrayLen;i++)
    {
        if(sum + array[i]>=array[i])
        {
            sum +=array[i];
            tmp_cnt+=1;
        }
        else {
			if(sum<array[i])
				start = i;
            sum = array[i];
           tmp_cnt=1;
        }
        if(sum >= max_sum)
        {
            max_sum = sum;
            cnt = tmp_cnt;
        }
    }
    *returnSize = cnt;
    return array+start;
}

发表于 2023-06-17 17:53:12 回复(0)
1、在连续子数组的基础上,记录起始点和结束点,注意因为要求最长,所以在最大值处要加上判断等于
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param array int整型vector 
     * @return int整型vector
     */
vector<int> FindGreatestSumOfSubArray(vector<int>& array) {
        // write code here
        int max=-100,sum=0,left=0,right=0,temp=0;
        for(int i=0;i<array.size();i++)
        {
            if(sum<0)
            {
                sum = array[i];
                if(max<=sum||max>0)
                    temp = i;
            }
            else
            {
                sum += array[i];
            }
            if(max<=sum)
            {
                max = sum;
                left = temp;
                right = i;
            }
        }
            
        return vector<int>(array.begin()+left,array.begin()+right+1);
    }
};


发表于 2022-01-15 21:49:56 回复(0)