[英]Maximum sum subarray such that start and end values are same
给定一个由 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 开始和结束,总和 = 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}。
尝试这个。
public static int solution(int[] array) {
Map<Integer, Integer> map = new HashMap<>();
int max = -1;
for (int i = 0, size = array.length; i < size; ++i) {
int value = array[i];
Integer start = map.get(value);
if (start != null)
max = Math.max(max, IntStream.rangeClosed(start, i).map(j -> array[j]).sum());
else
map.put(value, i);
}
return max;
}
public static void main(String[] args) {
System.out.println(solution(new int[] {1, 3, 2, 2, 3}));
System.out.println(solution(new int[] {5, 1, 4, 3}));
}
输出:
10
-1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.