【LeetCode】35.最大子序和

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/ca1m0921/article/details/89578784

leectCode 35.最大子序和  题目

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

示例:

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

如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。

我第一次的解法:

暴力嵌套循环:O(N^2)

class Solution {
    public int maxSubArray(int[] nums) {
        int max = nums[0];
		for(int i = 0; i < nums.length; i++){
			int temp = 0;
			for(int j = i; j < nums.length; j++){		
				temp += nums[j];
				if(max < temp){
					max = temp;
				}
			}
		}
		return max;
    }
}

leetCode评级:

找不到 图片了。  时间 长达 112mx  内存占用 37M

第二次

看了 B站老师的讲解之后,提交代码:  时间复杂度 O(2n) 

最大子序和 讲解地址:https://www.bilibili.com/video/av18586085/?p=8

特别注意 老师没有考虑 负数的问题,她的算法复杂度是 O(n).过不了LeetCode 的测试,故我加了一层for 复杂度编程 O(2n)

class Solution {
    public int maxSubArray(int[] nums) {
       int max = nums[0];
		int thisNums = 0;
		for(int i = 0; i < nums.length-1; i++){
			if(nums[i+1] > nums[i]){
				max = nums[i+1];
			}
		}
		for(int i = 0; i < nums.length; i++){
			thisNums += nums[i];	
			if(thisNums > max){
				max = thisNums;	
			}else if(thisNums < 0){
				thisNums = 0;
			}
		}
		return max;
    }
}

LeetCode 评级:

0

0

猜你喜欢

转载自blog.csdn.net/ca1m0921/article/details/89578784
今日推荐