首页 > 编程语言 > 详细

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

时间:2018-06-21 10:04:07      阅读:175      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!