概述
package utils;
public class LenggestSubsum {
public static void main(String[] args) {
long before = System.currentTimeMillis();
int[] a = {-2,1,-3,4,-1,2,1,-5,4};
//暴力发
// int b= common(a);
//分治法
// int b= divideAndConquer(a,0,a.length-1);
//求前n项和
int b = beforeSum(a);
System.out.println(b);
long current = System.currentTimeMillis();
System.out.println(current-before);
}
/**
* 暴力法
* @param randomValue 要求的数组
* @return
*/
public static int common(int[] randomValue){
int max = randomValue[0];
int sum = 0;
for(int index = 0; index < randomValue.length; index++){
for(int end = index; end < randomValue.length; end++){
sum = 0;
for (int start = index; start < end; start++){
sum += randomValue[start];
}
if (sum > max){
max = sum;
}
}
}
return max;
}
/**
* 分治法
* @param randomArr 求解的数组
* @param from 起始下标
* @param to 结束下标
* @return
*/
public static int divideAndConquer(int[] randomArr, int from, int to){
if(from == to){
return randomArr[0];
}
int middle = (to+from)/2;
int leftMax = divideAndConquer(randomArr,from,middle);
int rightMax = 0;
if ((middle + 1) <= to){
rightMax = divideAndConquer(randomArr,middle+1, to);
}
int lsum = 0;
int lmax = randomArr[middle];
int middleDecreaseOne = middle-1;
if(middleDecreaseOne >= from){
for(int i = middleDecreaseOne; i >= from; i--){
lsum += randomArr[i];
lmax = maxFromTwo(lsum, lmax);
}
}
int rsum = 0;
int middleInc = middle + 1;
if(middleInc <= to && middleInc < randomArr.length){
int rmax = randomArr[middleInc];
for(int i = middle + 2; i <= to; i++){
rsum += randomArr[i];
rmax = maxFromTwo(rsum, rmax);
}
}
int max = 0;
max = lsum + rsum;
return maxFromThree(leftMax, rightMax, max);
}
public static int maxFromTwo(int first, int seconde){
if(first > seconde)
return first;
else
return seconde;
}
public static int maxFromThree(int first, int second, int third){
int max = maxFromTwo(first,second);
return maxFromTwo(max, third);
}
/**
* 求前面n项的和,进行比较
* @param randomArr
* @return
*/
public static int beforeSum(int[] randomArr){
int result = randomArr[0];
int sum = randomArr[0];
for(int i = 1; i<randomArr.length; i++){
if (sum > 0){
sum += randomArr[i];
}else {
sum = randomArr[i];
}
if (sum > result){
result = sum;
}
}
return result;
}
}
最后
以上就是靓丽人生为你收集整理的数组最大和子系列的全部内容,希望文章能够帮你解决数组最大和子系列所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复