Leetcode 53. Maximum Subarray

xiaoxiao2021-02-28  66

Leetcode 53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

思路 :

连续子数组最大和问题,当以第i-1 个数字结尾的子数组的和,小于0时,如果把这个负数与第i 个数相加,得到的结果第i 个数本身还要小,所以此时不能把它加到第i 个数上。

sum条件sum = nums[i]如果当前的sum 小于0sum = sum + nums[i]如果当前的sum 大于0 class Solution { public int maxSubArray(int[] nums) { int max = nums[0]; int sum = nums[0]; for(int i = 1; i < nums.length; i++) { if(sum <= 0) { sum = nums[i]; }else { sum += nums[i]; } max = Math.max(max, sum); } return max; } }

注:学渣心里苦,不要学楼主,平时不努力,考试二百五,哭 ~

转载请注明原文地址: https://www.6miu.com/read-75416.html

最新回复(0)