題目英文
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. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “回溯”類算法
11. “數值分析”類算法