天天看點

[LeetCode-53]- Maximum Subarray(子數組最大值)

文章目錄

    • 題目相關
    • Solution

題目相關

【題目解讀】

擷取數組中最大子串,并傳回該最大值

【題目】原題連結

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;