Java implementation LeetCode 689 three non-overlapping sub-arrays, and a maximum (in other direction filtering)

689. The three non-overlapping sub-arrays and the maximum

Nums given array composed of a positive integer, to find the maximum and three non-overlapping sub-arrays.

The length of each sub-array is k, we will bring the 3 * k entries and maximized.

Back to start index list for each section (starting with index 0). If there are multiple results, returns a lexicographically smallest.

Example:

Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: subarray [1, 2], [2, 6], [7, 5 ] corresponds to the start index to [0, 3, 5].
We can also take [2, 1], but the results [1, 3, 5] larger in lexicographic order.
note:

nums.length range [1, 20,000] between.
nums [i] in the range [1, 65535] between.
k in the range [1, floor (nums.length / 3 )] between.

class Solution {
   private int maxSum;

    public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
       

        int n = nums.length;

        int[] sum = new int[n+1], left = new int[n], right = new int[n];

        for(int i=0; i<n; i++){
            sum[i+1] = sum[i]+nums[i];
        }
        //从左面筛选
        for(int i=k, leftmax = sum[k]-sum[0]; i<n ;i++){
            if(sum[i+1]-sum[i+1-k] > leftmax){
                leftmax = sum[i+1] - sum[i+1-k];
                left[i] = i+1-k;
            }else{
                left[i] = left[i-1];
            }
        }
        //右面筛选
        right[n-k] = n-k;
        for(int i=n-k-1, rightMax = sum[n]-sum[n-k]; i>=0; i--){
            if(sum[i+k]-sum[i]>= rightMax){
                right[i] = i;
                rightMax = sum[i+k] - sum[i];
            }else{
                right[i] = right[i+1];
            }
        }
        //去中间找,然后记录总和
        int maxsum = 0; int[] result = new int[3];
        for(int i=k; i<=n-2*k; i++){
            int l = left[i-1], r = right[i+k];
            int total = (sum[i+k]-sum[i]) + (sum[l+k] - sum[l]) + (sum[r+k]-sum[r]);
            if(total>maxsum){
                maxsum = total;
                result[0] = l; result[1] = i; result[2] =r;
            }
        }

        return result;

       
    } 
}
Released 1738 original articles · won praise 30000 + · views 3.66 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105329481