Title description:
Given an array sequence, it is required to select an interval so that the interval is the largest value among all the intervals calculated as follows:
The smallest number in the interval * the sum of all the numbers in the interval and the final program output the calculated maximum value. There is no need to output the collective interval.
For a given sequence [6 2 1], according to the above formula, all the calculated values that can be selected for each interval can be obtained.
[6]=6*6=36;
[2]=2*2=4;
[1]=1*1=1;
[6,2]=2*8=16;
[2,1]=1*3=3;
[6,2,1]=1*9=9;
From the above calculation, it can be seen that the selected interval [6], the calculated value is 36, and the program outputs 36.
All numbers in the interval are in the range of [0,100].
Enter a description:
Enter the length of the array sequence in the first line, and enter the array sequence in the second line.
For 50% of the data: 1<=n<=10000;
For 100% data: 1<=n<=500000;
Output description:
The calculated maximum value of the output array.
Code:
import java.util.Scanner;
public class MaxRange {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
in.close();
System.out.println(getMax(arr, 0, n - 1));
}
private static int getMax(int[] arr, int start, int end) {
if (arr == null || start > end) {
return 0;
}
int n = end - start + 1;
int[][] min = new int[n + 1][n + 1];
int[] sum = new int[n + 1];
sum[0] = 0;
// sum[i]即从第一个数加到第i个数的和,也就是arr[0]+...+arr[i-1]
for (int i = start + 1; i <= end + 1; i++) {
sum[i - start] = sum[i - start - 1] + arr[i - start - 1];
}
int max = -1;
for (int k = 0; k <= end - start; k++)
// 左右下标的差,k==0时,区间内有1个数
for (int i = 0; i <= end - start - k; i++) {
int j = i + k;
if (k == 0) {
min[i][j] = arr[i];
} else {
if (arr[j] < min[i][j - 1]) {
min[i][j] = arr[j];
} else {
min[i][j] = min[i][j - 1];
}
}
max = Math.max(max, min[i][j] * (sum[j + 1] - sum[i]));
}
return max;
}
}