课上的问题:
给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
这个题当时我并不是很清楚是到底该怎样,后来还是需要查阅资料,翻别人的代码去参考,但是我现在还是不太明白。
有个分治的办法,我拿来和大家一起分享一下:
package com.lhc.zixuhe; public class Fenzhi { int FindMaxCrossSubarray(int[] A,int low, int mid,int high) { int left_sum = -1000000000; int sum = 0; for (int i = mid; i>= low; i--) { sum += A[i]; if (sum>left_sum) { left_sum=sum; } } int right_sum = -100000000; sum = 0; for (int i = mid + 1; i <= high; i++) { sum += A[i]; if (sum > right_sum) { right_sum = sum; } } return left_sum + right_sum; } int FindMaxSubarray(int A[], int low, int high) { int left_sum, right_sum, cross_sum; if (high == low) { return A[low]; } else { int mid = (low + high) / 2; left_sum = FindMaxSubarray(A, low, mid); right_sum = FindMaxSubarray(A, mid + 1, high); cross_sum = FindMaxCrossSubarray(A, low, mid, high); if (left_sum >= right_sum && left_sum >= cross_sum) return left_sum; else if (right_sum >= left_sum && right_sum >= cross_sum) return right_sum; else return cross_sum; } } public static void main(String[] args) { int[] a = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 }; int length = a.length; Fenzhi b = new Fenzhi(); System.out.println(b.FindMaxSubarray(a, 0, length - 1)); } }
这个就是利用一个递归的思想来解决这个问题。