Given an array of integers, find a contiguous subarray which has the largest sum.
Return the sum of the subarray.
给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6
1、暴力 O(n2)
public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int maxSum = Integer.MIN_VALUE; for(int i=0; i<nums.length; i++){ int sum = 0; //必须定义在第一个for内部 for(int j=i; j<nums.length; j++){ sum += nums[j]; maxSum = Math.max(maxSum, sum); } } return maxSum; }
2、贪婪算法
public int maxSubArray(int[] A) { if(A==null || A.length==0){ return 0; } int maxSum = Integer.MIN_VALUE; int sum = 0; for(int i=0; i<A.length; i++){ sum += A[i]; maxSum = Math.max(maxSum, sum); sum = Math.max(sum, 0);//最关键 --sum 为负数时,令sum为0 } return maxSum; }
3、同方法2一样
public int maxSubArray(int[] nums) { int maxsum = Integer.MIN_VALUE; int sum = 0; for (int i = 0; i < nums.length; i++) { if (sum < 0) { sum = 0; } sum += nums[i]; maxsum = Math.max(maxsum, sum); } return maxsum; }
4、动态规划
public int maxSubArray(int[] nums) { int max_ending_here = nums[0]; //包括当前位置时候的最大值 int max_so_far = nums[0]; // 最大值 for (int i = 1; i < nums.length; i++) { max_ending_here = Math.max(nums[i], nums[i] + max_ending_here); max_so_far = Math.max(max_so_far, max_ending_here); } return max_so_far; }
最小子数组
public int minSubArray(ArrayList<Integer> nums) { int min_ending_here = nums.get(0); int min_so_far = nums.get(0); for (int i=1 ;i< nums.size(); i++){ min_ending_here = Math.min(nums.get(i),nums.get(i) + min_ending_here); min_so_far = Math.min( min_so_far, min_ending_here ); } return min_so_far; }
时间: 2024-12-11 16:57:13