LeetCode-剑指offer42-连续子数组的最大和

题目

输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

要求时间复杂度为O(n)。

示例:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

 

思路

动态规划

状态转移方程:dp[i] = max( nums[i] , dp[i-1] + num[i] )

 

 1 public int maxSubArray(int[] nums) {
 2 
 3         if (nums.length == 1) return nums[0];
 4         if (nums.length == 0) return 0;
 5 
 6         for(int i=1;i<nums.length;i++) {
 7             
 8             
 9              nums[i] = Math.max(nums[i],nums[i-1]+nums[i]);
10             
11         }
12         
13         int max = Integer.MIN_VALUE;
14         
15         for(int i=0;i<nums.length;i++) {
16             
17             max = Math.max(max, nums[i]);
18             
19         }
20         
21         return max;
22     }

 

posted @ 2020-07-16 16:02  垫底研究生小莫  阅读(146)  评论(0编辑  收藏  举报