【问题标题】:Maximum sum subarray such that start and end values are same最大和子数组,使得开始值和结束值相同
【发布时间】: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}。

【问题讨论】:

标签: java arrays hashmap sub-array


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 2013-11-20
    • 1970-01-01
    • 2022-12-12
    • 2016-05-02
    • 2011-08-28
    相关资源
    最近更新 更多