【发布时间】:2021-12-20 13:56:29
【问题描述】:
给定一个由 N 个正数组成的数组,任务是找到一个连续子数组 (LR),使得 a[L]=a[R] 和 a[L] + a[L+1] +…+ a[R] 为最大值。如果数组没有相同的数字,则返回 -1。
例如:
输入:arr[] = {1, 3, 2, 2, 3} 输出:10 子数组 [3, 2, 2, 3] 以 3 开始和结束,并且 sum = 10
输入:arr[] = {5,1,4,3} 输出:-1
public int solution(int[] A) {
// write your code in Java SE 8
int n = A.length;
HashMap<Integer, Integer> first = new HashMap<>();
HashMap<Integer, Integer> last = new HashMap<>();
int[] prefix = new int[n];
for (int i = 0; i < n; i++) {
// Build prefix sum array
if (i != 0)
prefix[i] = prefix[i - 1] + A[i];
else
prefix[i] = A[i];
// If the value hasn't been encountered before,
// It is the first occurrence
if (!first.containsKey(A[i]))
first.put(A[i], i);
// Keep updating the last occurrence
last.put(A[i], i);
}
int ans = -1;
// Find the maximum sum with same first and last
// value
for (int i = 0; i < n; i++) {
int start = first.get(A[i]);
int end = last.get(A[i]);
int sum = 0;
if(start == 0)
sum = prefix[end];
else
sum = prefix[end] - prefix[start - 1];
if(sum > ans)
ans = sum;
}
return ans;
}
对于示例,它不返回 -1:arr[] = {5,1,4,3}。
【问题讨论】:
-
恕我直言,没有“错误”:您的算法有错误的方法。保留两张地图,一张用于位置,一张用于累积总和。剩下的就看你了。见Open letter to students with homework problems
标签: java arrays hashmap sub-array