LeetCode實戰:最大子序和

題目英文

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.


題目中文

給定一個整數數組 nums,找到一個具有最大和的連續子數組(子數組最少包含一個元素),返回其最大和。

示例 1:

輸入: [-2,1,-3,4,-1,2,1,-5,4],
輸出: 6
解釋: 連續子數組 [4,-1,2,1] 的和最大,爲 6

示例 2:

輸入: [-2,1],
輸出: 1

進階:

如果你已經實現複雜度爲 O(n) 的解法,嘗試使用更爲精妙的分治法求解。


算法實現

利用暴力算法

public class Solution {
    public int MaxSubArray(int[] nums) {
        int len = nums.Length;
        if (len == 0)
            return 0;
        if (len == 1)
            return nums[0];
        int max = int.MinValue;

        for (int i = 0; i < len; i++)
        {
            int sum = nums[i];
            if (sum > max)
            {
                max = sum;
            }
            for (int j = i + 1; j < len; j++)
            {
                sum += nums[j];
                if (sum > max)
                {
                    max = sum;
                }
            }
        }
        return max;        
    }
}

利用動態規劃

動態規劃的最優子結構如下:

max[i] = Max(max[i-1] + nums[i], nums[i])
public class Solution {
    public int MaxSubArray(int[] nums) {
        int len = nums.Length;
        if (len == 0)
            return 0;
        if (len == 1)
            return nums[0];
        int[] max = new int[len];
        max[0] = nums[0];
        int result = max[0];
        for (int i = 1; i < len; i++)
        {
            if (max[i - 1] + nums[i] > nums[i])
                max[i] = max[i - 1] + nums[i];
            else
                max[i] = nums[i];

            if (max[i] > result)
            {
                result = max[i];
            }
        }
        return result;      
    }
}

實驗結果

利用暴力算法

  • 狀態:通過
  • 202 / 202 個通過測試用例
  • 執行用時: 596 ms, 在所有 C# 提交中擊敗了 14.18% 的用戶
  • 內存消耗: 24.5 MB, 在所有 C# 提交中擊敗了 5.88% 的用戶

提交結果

利用動態規劃

  • 狀態:通過
  • 202 / 202 個通過測試用例
  • 執行用時: 136 ms, 在所有 C# 提交中擊敗了 91.85% 的用戶
  • 內存消耗: 24.4 MB, 在所有 C# 提交中擊敗了 5.88% 的用戶

提交結果


相關圖文

1. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “回溯”類算法

11. “數值分析”類算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章