腾讯笔试第四题,剩20%过不了,求教

import java.util.Scanner;

public class Main {
	public static int minIndex = 0;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int number[] = new int[n];
		for(int i=0;i<n;i++)
		{
			number[i]=in.nextInt();
		}
		System.out.println(compare(number,0,n-1));
	}
	
	public static long compare(int[] number, int start, int end)
	{
		if(start>end)
			return 0;
		long sum =  maxSum(number,start,end);
		return Math.max(sum,Math.max(compare(number, start,minIndex-1),
									 compare(number, minIndex+1,end)));
	}
	
	public static long maxSum(int[] number, int start, int end)
	{
		int min = Integer.MAX_VALUE;
		long sum = 0;
		for(int i=start;i<=end;i++)
		{
			if(min>number[i])
			{
				min = number[i];
				minIndex = i;
			}
			sum += number[i];
		}
		return min*sum;
	}
}

思路:
对整个数组a[n],最小值序号为index,最大值出现的三种情况:
  1. start = 0, end = n-1,即覆盖整个数组
  2. start = 0, end = index-1,即出现在最小值左边
  3. start = index+1, end = n-1,即出现在最小值右边
这里左右都去掉了最小值,因为不去掉的话,最大的一定是整个数组。
然后对左边和右边递归,得出的结果取最大值。

但最后只过了80%,求教!
#腾讯##笔试题目#
全部评论

相关推荐

01-12 09:24
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
3
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务