[leetcode]53. Maximum Subarray最大子数组和
Posted 程序媛詹妮弗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]53. Maximum Subarray最大子数组和相关的知识,希望对你有一定的参考价值。
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题意:
求最大子数组和
思路:
一维dp
原理:任何数加负数肯定比原值小
dp[i]表示第i个元素能取到的最大值
dp[i] = dp[i-1] >0 ? dp[i-1] + num[i] : num[i]
代码:
1 class Solution { 2 public int maxSubArray(int[] nums) { 3 int[] dp = new int[nums.length]; 4 dp[0] = nums[0]; 5 int maxResult = nums[0]; 6 7 for(int i = 1; i < nums.length; i++){ 8 dp[i] = dp[i-1] > 0 ? dp[i-1] + nums[i] : nums[i] ; 9 maxResult = Math.max(maxResult, dp[i]); 10 } 11 return maxResult; 12 } 13 }
以上是关于[leetcode]53. Maximum Subarray最大子数组和的主要内容,如果未能解决你的问题,请参考以下文章