首先,定义一个dp数组,大小和nums数组的大小一致,
dp[i] 定义为数组nums 中以num[i] 结尾的最大连续子串和,
则有dp[i] = max(dp[i-1] + nums[i], num[i]),对应着取和不取两种状态,如果dp[i-1]为负数,自然就不取。
代码如下:
public static int f(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i- 1] + nums[i], nums[i]);
if (max < dp[i]) {
max = dp[i];
}
}
return max;
}
HDU_1003问题代码:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int count = 0;
while(count ++ != t) {
int size = sc.nextInt();
int[] nums = new int[size];
int[] a = new int[2];
for (int i = 0; i < size; i++) {
nums[i] = sc.nextInt();
}
int max = f(nums,a);
findFirst(nums,a,max);
if (count != t) {
System.out.println(String.format("Case %d:",count));
System.out.println(max+" " + a[0] + " " + a[1]);
System.out.println();
} else {
System.out.println(String.format("Case %d:",count));
System.out.println(max+" " + a[0] + " " + a[1]);
}
}
}
public static int f(int[] nums, int[] a) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = nums[0];
a[0] = a[1] = 1;
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i- 1] + nums[i], nums[i]);
if (max < dp[i]) {
max = dp[i];
a[1] = i+1;
}
}
return max;
}
static void findFirst(int[] nums, int[] a, int max) {
int sum = 0;
for (int i = a[1] - 1; i >= 0 ; i--) {
sum += nums[i];
if (sum == max) {
a[0] = i + 1;
}
}
}
}
时间复杂度O(N)
空间复杂度O(N)
附上其他解法:
分治:https://blog.csdn.net/qq_43619527/article/details/104469856
贪心:https://blog.csdn.net/qq_43619527/article/details/104470534