这是在OA中提出的.给定一个大小为n
的正整数array.
对于数组中的每个项目(索引范围从0
到n - 1
),找到包含当前项目的最大子数组的大小,使得当前项目等于该子数组中的最大元素,并将该大小添加到结果(从0开始).
Example:
arr = [3,5,6]
Result = 6
Explanation:
i=0 => [3] = max subarray with 3 as maximum, size of sub-array is 1
i=1 => [3,5] = max subarray with 5 as maximum, size of sub-array is 2
i=2 => [3,5,6] = max subarray with 6 as maximum, size of sub-array is 3
Sum = 1 + 2 + 3 = 6
Example:
arr = [ 1,2,1]
Result = 5
Explanation:
i = 0 => [1] max subarray, size = 1
i = 1 => [1, 2, 1] max subarray with 2 as maximum, size = 3
i = 2 => [1], max subarray with 1 as maximum, size = 1
Result = 1 + 3 + 1 = 5
Example:
arr = [1,1,1,1]
Result = 16
Explanation:
i = 0 => [1, 1, 1, 1] max subarray with 1 as maximum, size = 4
Same for i=1, 2, 3 => max subarray for each case is still [1,1,1,1] with size 4
Result = 4 + 4 + 4 + 4 = 16
下面是我的代码:
public class Main {
public static int solve(int[] arr) {
int n = arr.length;
int result = 0;
int currentMax = Integer.MIN_VALUE;
int size = 0;
for (int i = 0; i < n; i++) {
currentMax = Math.max(currentMax, arr[i]);
if (arr[i] == currentMax) {
size++;
int backUp = size;
for(int j=i+1; j<n; j++) {
if(arr[j] <= currentMax) {
size++;
} else {
break;
}
}
result += size;
size = backUp;
} else {
size = 1;
currentMax = arr[i];
result++;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(solve(new int[]{3,5,6}));//6
System.out.println(solve(new int[]{1,2,1}));//5
System.out.println(solve(new int[]{1,1,1,1}));//16
}
}
我的代码只适用于示例测试用例,而对于隐藏的其他用例则失败了,所以我无法看到它们.什么是正确的方法来解决这个问题,测试用例失败说错误的输出,没有超时错误.