Leet Code 53 Maximum Subarray - 子数组最大和 - Java
2016-06-23 00:00
459 查看
摘要: Leet Code 53 Maximum Subarray - 子数组最大和 - Java
问题原始链接 https://leetcode.com/problems/maximum-subarray
找到数组中连续子数组(至少包含一个元素)的最大和。
例如,给定数组 [−2,1,−3,4,−1,2,1,−5,4],连续子数组 [4,−1,2,1] 有最大和 6。
使用动态规划法。设数组为a,长度为n,申请一个整数数组 dp
,dp[i]表示以a[i]结尾的子数组的最大和。dp[0]=a[0],如果dp[i-1]<=0,则d[i]=a[i],如果dp[i-1]>0,则dp[i]=dp[i-1]+a[i]。最终结果为dp数组中的最大值。
问题原始链接 https://leetcode.com/problems/maximum-subarray
找到数组中连续子数组(至少包含一个元素)的最大和。
例如,给定数组 [−2,1,−3,4,−1,2,1,−5,4],连续子数组 [4,−1,2,1] 有最大和 6。
使用动态规划法。设数组为a,长度为n,申请一个整数数组 dp
,dp[i]表示以a[i]结尾的子数组的最大和。dp[0]=a[0],如果dp[i-1]<=0,则d[i]=a[i],如果dp[i-1]>0,则dp[i]=dp[i-1]+a[i]。最终结果为dp数组中的最大值。
[code=language-java]public class Solution { public static int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int max = nums[0]; dp[0] = nums[0]; for (int i = 1; i < nums.length; i++) { dp[i] = dp[i - 1] <= 0 ? nums[i] : dp[i - 1] + nums[i]; if (dp[i] > max) { max = dp[i]; } } return max; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解