-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q24_最大子数组.java
80 lines (74 loc) · 2.72 KB
/
Q24_最大子数组.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.algorithm.demo.array;
public class Q24_最大子数组 {
public static void main(String[] args) {
int[] array = {1, -2, 3, 10, -4, 7, 2, -5};
Long begintime = System.nanoTime();
int result = maxSubArray(array);
Long endtime = System.nanoTime();
System.out.println("连续子数组的最大和为:" + result + ",运行时间:" + (endtime - begintime) + "ns");
}
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public static int maxSubArray(int[] nums) {
int len = nums.length;
if (len == 0) {
return 0;
}
int currentsum = nums[0];
int greatsetsum = nums[0];
System.out.println("第1步:累加子数组和:" + currentsum + ",最大子数组和:" + greatsetsum);
for (int i = 1; i < nums.length; i++) {//{1, -2, 3, 10, -4, 7, 2, -5};
if (currentsum > 0) {
currentsum += nums[i];
} else {
currentsum = nums[i];
}
if (currentsum > greatsetsum) {
greatsetsum = currentsum;
}
System.out.println("第" + (i + 1) + "步:累加子数组和:" + currentsum + ",最大子数组和:" + greatsetsum);
}
return greatsetsum;
}
public static int FindGreatestSumOfSubArray(int[] array) {
int len = array.length;
if (len == 0){
return 0;
}
int[] currentsum = new int[len];
currentsum[0] = array[0];
int greatsetsum = array[0];
System.out.println("第1步:累加子数组和:"+currentsum[0]+",最大子数组和:"+greatsetsum);
for(int i=1;i<array.length;i++){
//下面是动态规划的状态转移方程
if(currentsum[i-1]>0){
currentsum[i] = currentsum[i-1] + array[i];
}else{
currentsum[i] = array[i];
}
//根据currentsum的值更新greatsetsum的值
if(currentsum[i] > greatsetsum){
greatsetsum = currentsum[i];
}
System.out.println("第"+(i+1)+"步:累加子数组和:"+currentsum[i]+",最大子数组和:"+greatsetsum);
}
return greatsetsum;
}
public static int maxSubArray2(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for(int i = 1; i < nums.length; i++){
if(currentSum > 0){
currentSum += nums[i];
}else{
currentSum = nums[i];
}
if(maxSum < currentSum){
currentSum = maxSum;
}
}
return maxSum;
}
}