Max double slice sum

前端 未结 14 1158
后悔当初
后悔当初 2020-12-13 20:53

Recently, I tried to solve the Max Double Slice Sum problem in codility which is a variant of max slice problem. My Solution was to look for a slice that has maximum value w

14条回答
  •  天涯浪人
    2020-12-13 21:10

    Think I got it based on Moxis Solution. Tried to point out the Intension.

        class Solution {
        public int solution(int[] A) { 
    
        int n = A.length - 1;
    
        // Array with cummulated Sums when the first Subarray ends at Index i
        int[] endingAt = new int[A.length];
        int helperSum = 0;
    
        // Optimal Subtotal before all possible Values of Y
        for(int i = 1; i < n; ++i ) {            
            helperSum = Math.max(0, A[i] + helperSum);
            endingAt[i] = helperSum;
        }
    
        // Array with cummulated Sums when the second Subarray starts at Index i
        int[] startingAt = new int[A.length];
        helperSum = 0;
    
        // Optimal Subtotal behind all possible Values of Y
        for(int i = (n - 1); i > 0; --i ) {   
            helperSum = Math.max(0, A[i] + helperSum);
            startingAt[i] = helperSum;
        }
    
        //Searching optimal Y
        int sum = 0;
        for(int i = 0; i < (n - 1); ++i) {
            sum = Math.max(sum, endingAt[i] + startingAt[i+2]);
        }
    
        return sum;
    
    }
    

    }

提交回复
热议问题