LeetCode——Maximum Subarray

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

  • Example:
    Input: [-2,1,-3,4,-1,2,1,-5,4],
    Output: 6
    Explanation: [4,-1,2,1] has the largest sum = 6.

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.

解法一——时间复杂度(N)

public int maxSubArray(int[] nums) {
	     if(nums==null||nums.length==0)
	    	 return 0;
	     int max=nums[0],cur=nums[0];
		 for(int i=1;i<nums.length;i++)
		 {
			 cur+=nums[i];
			 if(cur<nums[i])
				 cur=nums[i];
			 if(max<cur)
				 max=cur;
		 }
		 return max;
	 }

Runtime: 6 ms, faster than 99.95% of Java online submissions for Maximum Subarray.
Memory Usage: 38.7 MB, less than 89.31% of Java online submissions for Maximum Subarray.
简洁一点的写法

 public int maxSubArray(int[] nums) {
	     if(nums==null||nums.length==0)
	    	 return 0;
	     int max=nums[0],cur=nums[0];
		 for(int i=1;i<nums.length;i++)
		 {
			  cur=cur+nums[i]>nums[i]?cur+nums[i]:nums[i];
			 max=max>cur?max:cur;
		 }
		 return max;
	 }

Runtime: 6 ms, faster than 99.95% of Java online submissions for Maximum Subarray.
Memory Usage: 38.8 MB, less than 87.05% of Java online submissions for Maximum Subarray.

解法二——分治思想(时间复杂度O(NlogN))

分治思想看了一位博主写的代码

public int maxSubArray(int[] nums) {
	     if (nums.length == 0) return 0;
	     return helper(nums, 0, nums.length - 1);
	 }
	 public int helper(int[] nums, int left, int right) {
	     if (left >= right) return nums[left];
	     int mid =  (right+left) / 2;
	     int lmax = helper(nums, left, mid - 1);
	     int rmax = helper(nums, mid + 1, right);
	     int mmax = nums[mid], t = mmax;
	     for (int i = mid - 1; i >= left; --i) {
	         t += nums[i];
	         mmax = Math.max(mmax, t);
	     }
	     t = mmax;
	     for (int i = mid + 1; i <= right; ++i) {
	         t += nums[i];
	         mmax = Math.max(mmax, t);
	     }
	     return Math.max(mmax, Math.max(lmax, rmax));
	 }

Runtime: 7 ms, faster than 73.88% of Java online submissions for Maximum Subarray.
Memory Usage: 38.7 MB, less than 90.04% of Java online submissions for Maximum Subarray.

你可能感兴趣的:(算法)