【LeetCode】53. Maximum Subarray
2017-05-15 08:37
399 查看
问题描述
https://leetcode.com/problems/maximum-subarray/#/descriptionFind 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.
计算数组中的最大子串和。
算法分析
参考自:https://discuss.leetcode.com/topic/7447/o-n-java-solution因为数组中有正数也有负数,每加一个正数,子串值增加,每加一个负数,子串值减少,所以,应该尽量跳过负数。
下面使用
sum表示从左往右遍历数组时的当前较大子串和,总之,当前的那个数必须计算在
sum中。
sum初始化为
nums[0],接下来遍历到位置
1,有如下情况:
如果
nums[0]>=0,则
sum = sum + nums[1]
如果
nums[0]<0,则
sum = nums[1],
同理,有一般式:
sum = nums[i] + (sum<0?0:sum)
使用
max记录
sum变化过程中的最大值,即为答案。
代码
public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE, sum = 0; for (int i = 0; i < nums.length; i++) { sum = nums[i] + (sum < 0 ? 0:sum); max = sum > max ? sum:max; } return max; }
相关文章推荐
- LeetCode 53. Maximum Subarray
- [Leetcode] 53. Maximum Subarray 解题报告
- [LeetCode]53. Maximum Subarray
- [LeetCode] Algorithms-53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- leetcode_53. Maximum Subarray
- [勇者闯LeetCode] 53. Maximum Subarray
- [LeetCode]53. Maximum Subarray
- 【LeetCode】53. Maximum Subarray
- 【leetcode】53. Maximum Subarray
- 【leetcode】53. Maximum Subarray
- leetcode 53. Maximum Subarray
- leetcode 53. Maximum Subarray
- LeetCode 53. Maximum Subarray 题解
- [leetcode]53. Maximum Subarray 最大连续子串python实现【medium】
- LeetCode||53. Maximum Subarray
- [LeetCode] 53. Maximum Subarray 最大子数组
- Leetcode 53. Maximum Subarray
- 【Leetcode】Lee. 53. Maximum Subarray
- leetcode-53. Maximum Subarray