LeetCode(53):最大子序和 Maximum Subarray(Java)

2019.6.17 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

这是经典的数据结构与算法的入门题,也是我刷的第一道题,第一次打开了分治和DP的大门,原来算法是这么神奇的东西。

#数据结构与算法学习笔记#PTA4:分治算法求最大子列和(C/C++)

#数据结构与算法学习笔记#PTA3:在线处理算法求最大子列和,并返回最大子列和头尾元素(C/C++)(2004年浙大计科考研复试)


传送门:最大子序和

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

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.

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

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

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


/**
 * 
 * @author ChopinXBP
 * Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
 * 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
 *
 */

public class MaximumSubarray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] nums = {-2 , 1};
		int[] nums2 = {-2 , -1};
		System.out.println(maxSubArray(nums));
		System.out.println(maxSubArray(nums2));
	}
	
	//在线处理
	public static int maxSubArray(int[] nums) {
    	int result = nums[0];
    	int maxsubSum = 0;
    	for(int i = 0; i < nums.length; i++) {
    		maxsubSum += nums[i];
    		if(maxsubSum > result) {
    			result = maxsubSum;
    		}
    		if(maxsubSum < 0) {
    			maxsubSum = 0;
    		}
    	}
    	return result;
    }
		
	//分治算法
    public static int maxSubArray2(int[] nums) {
    	return Solution(nums, 0, nums.length - 1);
    }
    
    public static int MaxofThree(int a, int b, int c) {
    	return a > b ? (a > c ? a : c) : (b > c ? b : c);
    }
    
    public static int Solution(int[] nums, int begin, int end) {
    	if(begin == end) {
    		return nums[begin];
    	}
    	
    	int mid = (begin + end) >> 1;
    	int maxleftNum = Solution(nums, begin, mid);		//递归求左子列的最大子列和
    	int maxrightNum = Solution(nums, mid + 1, end);		//递归求右子列的最大子列和
    	
    	int leftSum = 0, maxmidleft = nums[mid];
    	for(int i = mid; i >= begin; i--) {
    		leftSum += nums[i];
    		if(leftSum > maxmidleft) {
    			maxmidleft = leftSum;
    		}
    	}
    	int rightSum = 0, maxmidright = nums[mid + 1];
    	for(int i = mid + 1; i <= end; i++) {
    		rightSum += nums[i];
    		if(rightSum > maxmidright) {
    			maxmidright = rightSum;
    		}
    	}
    	
    	return MaxofThree(maxleftNum, maxrightNum, maxmidleft + maxmidright);
    	
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

你可能感兴趣的:(数据结构与算法,JAVA,LeetCode)