-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSubarray005302.java
More file actions
50 lines (37 loc) · 1.18 KB
/
MaximumSubarray005302.java
File metadata and controls
50 lines (37 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 最大子序和,分治法版本
* 以前使用动态规划解,这版是分治法
*
*/
public class MaximumSubarray005302{
public static void main(String[] args) {
int nums[] = {-2, -1};
maxSubArray(nums);
}
public static int maxSubArray(int[] nums) {
int result = maxSum(nums, 0, nums.length-1);
System.out.println(result);
return result;
}
private static int maxSum(int[] nums, int start, int end) {
if (start >= end) {
return nums[start];
}
int mid = (start + end) / 2;
int leftMaxSum = maxSum(nums, start, mid);
int rightMaxSum = maxSum(nums, mid+1, end);
int tmpMaxLeft = Integer.MIN_VALUE;
int tmp = 0;
for (int i = mid; i >= start; i--) {
tmp += nums[i];
tmpMaxLeft = tmp >= tmpMaxLeft ? tmp : tmpMaxLeft;
}
int tmpMaxRight = Integer.MIN_VALUE;
tmp =0;
for (int i = mid+1; i <= end; i++) {
tmp += nums[i];
tmpMaxRight = tmp >= tmpMaxRight ? tmp : tmpMaxRight;
}
return Math.max(leftMaxSum, Math.max(rightMaxSum , tmpMaxLeft + tmpMaxRight));
}
}