**一. 题目描述**
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