62,616
社区成员
发帖
与我相关
我的任务
分享
//现有一个数组,求连续3个值相加的和最大是多少? 哪位有比较好的算法?
int a[] = {1,4,3,6,3,2,7,8,4,9,3,5,2}
package com.walkman.suanfa;
/**
* 作者: 严振
* 日期: 2011-7-11
* 内容: 求连续三个值相加的最大值
* 设计思想:用选择法,先取前三个数的和为最大值,循环进行比较。时间复杂度O(n)。
*/
public class MaxSum {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = {1,4,3,6,3,2,7,8,4,9,3,5,2};
int first_max = a[0] + a[1] + a[2]; //确定第一个为比较的值
int comp = 0;
for(int i = 1; i < a.length - 3; i++ ){
comp = a[i] + a[i+1] + a[i+2];
if(first_max < comp){
first_max = comp;
}
}
System.out.println("最大的和是: "+first_max);
}
}
public class Test {
static int a[] = {1,4,3,6,3,2,7,8,4,9,3,5,2};
static int N = 3;//连续N项和
public static void main(String[] args) {
System.out.println("连续" + N + "项和最大值为" + findMax(a, N));
}
/**count 为连续n项和*/
static int findMax(int[] num,int count){
if(num.length < count || count <= 0)
return Integer.MAX_VALUE * (-1); //数组长度过小,或者项数为非正
int sum = 0,max = Integer.MAX_VALUE * (-1);
for(int i = 0;i < count - 1;i++)
sum += num[i];
for(int i = count - 1;i < num.length;i++){
sum += num[i];
if(sum > max)
max = sum;
sum -= num[i - count + 1];
}
return max;
}
}
int max=0;
for (int i=0; i<a.length-2; i++) {
if (i==0 || (a[i] + a[i+1] + a[i+2]) > max)
max = a[i] + a[i+1] + a[i+2];
}
public static void main(String[] args) {
int a[] = {1,4,3,6,3,2,7,8,4,9,3,5,2};
int maxSum = 0;
int maxIndex = 0;
for(int i=0;i<a.length-3;i++){
int temp = a[i]+a[i+1]+a[i+2];
if(maxSum < temp){
maxSum = temp;
maxIndex = i;
}
}
System.out.println(maxSum);
System.out.println(maxIndex);
}