Recently, I encountered a lot of problems when I was looking for an internship and brushing the questions. There are some frustrations that I still report an error after 2 hours of coding, and I also have the loneliness of overcoming 100%. I would like to record one or two here and share my encouragement with you.
Given an integer array nums , find a contiguous subarray with the largest sum (the subarray contains at least one element), and return its largest sum (from leetcode53 problem).
Write a brute force recursion first
class Solution { public int maxSubArray(int[] nums) { return getMax(nums,nums.length-1); } private int getMax(int[] nums, int index) { if(index=0) { return nums[0]; } return Math.max(chosed(nums,index-1)+nums[index],getMax(nums, index-1)); } private int chosed(int[] nums,int index) { if(index<0) { return 0; } return Math.max(chosed(nums, index-1)+nums[index],0); } }
OJ actually passed. . .
I have been thinking about this recursive dynamic programming for a long time, and I feel that my thinking has become rigid. Baidu took a look and referred to the blogger.window rain tree snowThe method is written in O(n).
class Solution {
public int maxSubArray(int[] nums) {
int sum = 0;
int maxSum =Integer.MIN_VALUE;
//find the maximum value in nums
for (int i = 0; i < nums.length; i++) {
if(nums[i]>maxSum) {
maxSum = nums [i];
}
}
//When a number plus the previous sum is greater than the maximum, it is assigned, and it is impossible to be the start bit when it is less than zero
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if(sum>maxSum) {
maxSum = sum;
}else if(sum<0){
sum = 0;
}
}
return maxSum;
}
}
oj: 13ms, I don't know why, I can't insert pictures
, Okay, please correct me.
Unless otherwise marked and quoted, the above are all originals. If there is any infringement, please contact me to delete it.