腾讯笔试第四题,剩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,最大值出现的三种情况:
- start = 0, end = n-1,即覆盖整个数组
- start = 0, end = index-1,即出现在最小值左边
- start = index+1, end = n-1,即出现在最小值右边
然后对左边和右边递归,得出的结果取最大值。
但最后只过了80%,求教!
#腾讯##笔试题目#

格力公司福利 356人发布