【LeetCode】53. Maximum Subarray

我的相关文章:

【1】牛客网在线编程专题《剑指offer-面试题31》连续子数组的最大和


53. Maximum Subarray

Description:

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.

 解题思路:

(1)举例分析数组的规律

已经AC的代码:

public class solutionMaxSubArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
		System.out.println(maxSubArray(arr));
	}
	
    public static int maxSubArray(int[] nums) {
       int  sum = Integer.MIN_VALUE;
       int currentSum = 0;
       for(int i=0; i sum) {
    		   sum = currentSum;
    	   }
       }
       return sum;
    }

}

(2)动态规划的解法

public class solutionMaxSubArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
		System.out.println(maxSubArray(arr));
	}
	
    public static int maxSubArray(int[] nums) {
    	int sum = Integer.MIN_VALUE;
    	int currentSum = 0;
    	for(int i=0; i sum)
    			sum = currentSum;
    	}
		return sum;
    }
}

 

你可能感兴趣的:(LeetCode,算法,数组,算法,LeetCode)