Leetcode 53. Maximum Subarray

題目

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. 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.
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.

解析

尋找一個子串,使其之和最大。如果存在正數,那肯定從正數開始的子串之和比較大,這里使用的貪心法,依次計算,如果當前子串的和小于0,那么就放棄重新開始計算。如果數組中全是負數,就挑選一個相對較大的負數返回即可。
這里注意尋找最大值時的界限-2147483647,測試數據里面有該值。

int maxSubArray(int* nums, int numsSize) {
    int ans=-2147483647,temp=0;
    for(int i=0;i<numsSize;i++)
    {
        if(temp+nums[i]>0)
        {
            temp=temp+nums[i];
            if(temp>ans)
                ans=temp;
        }
        else
        {
            temp=0;
        }
    }
    for(int i=0;i<numsSize;i++)
    {
        if(nums[i]>ans)
            ans=nums[i];
    }
    return ans;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容