**一. 題目描述**
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`.
**二. 題目分析**
可使用動態規劃來解決。時間復雜度為O(n)。假設已知`0, .., k`的最大和`sum[k]`以后,則`0, ..., k+1`的最大和sum[k+1]分為以下兩種情況:?
1)若`sum[k]>=0`,則`sum[k+1]=sum[k]+A[k+1]`。?
2)若`sum[k]<0`,另起一個SubArray,令`sum[k+1]=A[k+1]`。
在計算過程中,使用一個變量`maxsum`用于存儲`sum`的最大值,一旦出現更大的`sum`值則更新之,最后返回該變量即可。
**三. 示例代碼**
~~~
int maxSubArray(int A[], int n)
{
if (n <= 0) return 0;
int sum = 0;
int maxsum = INT_MIN;
for (int i = 0; i < n; i++)
{
sum += A[i];
if (sum > maxsum) maxsum = sum;
if (sum < 0) sum = 0;
}
return maxsum;
}
~~~
**四. 小結**
該題是一道基礎的動態規劃題,盡管有多種其他方法可以實現。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching