[leetcode]53. Maximum Subarray
2017-03-24 13:29
351 查看
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
经典的动态规划问题。要求找出最大和的子串。定义两个变量res和sum,ress 是最终要返回的结果。每遍历一个数字num,比较sum + num和num中的较大值存入sum,然后再把res和sum中的较大值存入res,以此类推直到遍历完整个数组,。时间复杂度O(n)
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.
经典的动态规划问题。要求找出最大和的子串。定义两个变量res和sum,ress 是最终要返回的结果。每遍历一个数字num,比较sum + num和num中的较大值存入sum,然后再把res和sum中的较大值存入res,以此类推直到遍历完整个数组,。时间复杂度O(n)
public class Solution { public int maxSubArray(int[] nums) { if(nums==null || nums.length==0) return 0; int res = nums[0]; int sum = nums[0]; for(int i=1;i<nums.length;i++) { sum = Math.max(nums[i],sum+nums[i]); res = Math.max(sum,res); } return res; } }
相关文章推荐
- 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
- LeetCode53. Maximum Subarray
- LeetCode - 53. Maximum Subarray
- Leetcode 53. Maximum Subarray
- 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