leetcode 53. Maximum Subarray(DP动态规划问题)
2017-12-06 21:41
267 查看
问题描述:
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.
思路:
本题为最优解问题,可利用动态规划思路求解。从头到尾遍历每一个数组元素,如何前面元素的和为正,则加上本元素的值继续搜索;如何前面元素的和为负,则此元素开始新的和计数。整个过程中要注意更新和的最大值。
代码:
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.
思路:
本题为最优解问题,可利用动态规划思路求解。从头到尾遍历每一个数组元素,如何前面元素的和为正,则加上本元素的值继续搜索;如何前面元素的和为负,则此元素开始新的和计数。整个过程中要注意更新和的最大值。
代码:
class Solution { public int maxSubArray(int[] nums) { if(nums == null) return 0; int sum = 0; int max = Integer.MIN_VALUE; for(int i = 0 ; i < nums.length; i++){ if(sum + nums[i] > nums[i]) sum += nums[i]; else sum = nums[i]; if(sum > max) max = sum; } return max; } }
相关文章推荐
- leetcode 213. House Robber II 入室抢劫 抢劫问题 + 一道经典的DP动态规划问题
- leetcode 279. Perfect Squares 类似背包问题 + 很简单的动态规划DP解决
- leetcode 174. Dungeon Game 一个逆着推导计算的DP动态规划问题
- leetcode 322. Coin Change 类似背包问题 + 很简单的动态规划DP解决
- 动态规划之01背包问题及leetcode实例
- Sicily 1146 采药(DP动态规划——01背包问题)
- 动态规划:HDU1864-最大报销额(处理带小数的dp问题)
- 最优配对问题(集合上的动态规划) —— 状压DP
- 动态规划解TSP问题(状态压缩dp)
- leetcode 446. Arithmetic Slices II - Subsequence 等差序列的数量 + 一个很值得学习的DP动态规划做法
- DP动态规划问题(1)
- leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历 + 很明显很经典的DP动态规划做法
- C语言使用DP动态规划思想解最大K乘积与乘积最大问题
- LeetCode 70. Climbing Stairs 自顶向下记忆化搜索,自底向上重叠子问题动态规划
- leetcode 152. Maximum Product Subarray 最大连乘子序列 + 很棒的动态规划DP做法
- 程序设计实习动态规划练习 Charm Bracelet(0/1背包问题dp)
- DP动态规划问题 1300
- HDU5860(约瑟夫环问题。超级牛B的动态规划思维题,DP嘛,推出递推式谁不会写)
- 动态规划问题-DP 最大子段和O(n)解决方法
- 动态规划DP问题分类和经典题型