[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 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9206895.html