1 Star 0 Fork 3

aiobc/Algorithms

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
MaximumSubarray.java 1.10 KB
一键复制 编辑 原始数据 按行查看 历史
Rafael Chaves 提交于 2020-02-03 02:07 +08:00 . Adopt standard Java project layout (#120)
/**
* This file shows you how to find the maximal subarray in an integer array Time complexity: O(n)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.dp;
public class MaximumSubarray {
public static void main(String[] args) {
System.out.println(maximumSubarrayValue(new int[] {-5}));
System.out.println(maximumSubarrayValue(new int[] {-5, -4, -10, -3, -1, -12, -6}));
System.out.println(maximumSubarrayValue(new int[] {1, 2, 1, -7, 2, -1, 40, -89}));
}
// Return the value of the maximum subarray in 'ar'
public static long maximumSubarrayValue(int[] ar) {
if (ar == null || ar.length == 0) return 0L;
int n = ar.length, maxValue, sum;
maxValue = sum = ar[0];
for (int i = 1; i < n; i++) {
// At each step consider continuing the current subarray
// or starting a new one because adding the next element
// doesn't acutally make the subarray sum any better.
if (ar[i] > sum + ar[i]) sum = ar[i];
else sum = sum + ar[i];
if (sum > maxValue) maxValue = sum;
}
return maxValue;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aiobc/Algorithms.git
git@gitee.com:aiobc/Algorithms.git
aiobc
Algorithms
Algorithms
master

搜索帮助