Android Studio下使用Junit框架测试数组和

本文介绍了一个用于寻找数组中最大子数组和的Java程序实现。该算法通过迭代数组元素并维护一个累积变量来跟踪当前子数组的最大和,最终返回整个数组中的最大子数组之和。文章包含完整的代码示例及运行示例。
 1 public class Maxsum {
 2     public int maxsum(int[] array) {
 3         if (array == null || array.length == 0) {
 4             throw new IllegalArgumentException("array is null or empty.");
 5         }
 6 
 7 
 8         int result = array[0], mark = 0;
 9 
10         for (int i = 0; i < array.length; i++) {
11             int element = array[i];
12 
13             if (mark >= 0) {
14                 mark += element;
15             } else {
16                 mark = element;
17             }
18 
19             if (mark > result) {
20                 result = mark;
21             }
22         }
23         return result;
24     }
25 
26     public static void main(String[] args) {
27         Maxsum maxsum = new Maxsum();
28         int maxSum = maxsum.maxsum(new int[]{-2,2,-5,3,-4});
29         System.out.println(maxSum);
30     }

 

转载于:https://www.cnblogs.com/xiaonong/p/6567742.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值