码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]53. Maximum Subarray最大子数组和

时间:2018-06-21 11:32:42      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:exp   math   数组   style   ++   its   VID   lan   public   

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最大子数组和

标签:exp   math   数组   style   ++   its   VID   lan   public   

原文地址:https://www.cnblogs.com/liuliu5151/p/9206895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!