方法类:
package com.lwk.test2;
import java.util.Scanner;
public class Sum {
Scanner input = new Scanner(System.in);
public int sumParams(int nums[]) {
int maxSum = 0;
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum = sum + nums[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
System.out.println("子数组之和的最大值为:"+maxSum);
return maxSum;
}
}
测试类:
package com.lwk.test2;
import static org.junit.Assert.*;
import org.junit.Test;
public class SumTest {
@Test
public void test() {
/* int nums[] = {1,-2,3,5,-1}; */// 测试用例1 最大值8
/* int nums[] = {1,-2,3,-8,5,1}; */// 测试用例1 最大值6
int nums[] = { 1, -2, 3, -2, 5, 1 }; // 测试用例1 最大值7
Sum sum = new Sum();
sum.sumParams(nums);
}
}
测试用例有三个,可以根据自己需要添加不同的测试用例
时间: 2024-10-29 19:09:39