Finding two non-subsequent elements in array which sum is minimal

前端 未结 13 1008
小蘑菇
小蘑菇 2021-02-05 03:40

Intro: As far as I could search, this question wasn\'t asked in SO yet.
This is an interview question.
I am not even specifically looking for a code sol

13条回答
  •  抹茶落季
    2021-02-05 04:09

    I think this does not need any deep reasoning, and can be solved in a single pass, keeping the optimal solution of the array elements processed so far:

    public static int[] minimumSumOfNonAcjacentElements(int[] a) {
        // the result for the sequence a[1:i]
        int minSum = Integer.MAX_VALUE;
        int minSumElement1 = Integer.MAX_VALUE;
        int minSumElement2 = Integer.MAX_VALUE;
    
        // the minimum element eligible for joining with a[i], i.e. from a[1 : i-2]
        int minElement = a[1];
    
        int prevElement = a[2]; // a[i - 1]
        for (int i = 3; i + 1 < a.length; i++) {
            int sum = minElement + a[i];
            if (sum < minSum) {
                minSum = sum;
                minSumElement1 = minElement;
                minSumElement2 = a[i];
            }
    
            if (prevElement < minElement) {
                minElement = prevElement;
            }
            prevElement = a[i];
        }
    
        return new int[] {minSumElement1, minSumElement2};
    }
    

    Here's some test code, with the corner cases from OP's question:

    private static void test(int minSumIndex1, int minSumIndex2, int... input) {
        int[] result = minimumSumOfNonAcjacentElements(input);
        if (result[0] == minSumIndex1 && result[1] == minSumIndex2) {
            // ok
        } else {
            throw new AssertionError("Expected: " + minSumIndex1 + ", " + minSumIndex2 + ". Actual=" + Arrays.toString(result));
        }
    }
    
    public static void main(String[] args) throws Exception {
        test(2, 2, 4, 2, 1, 2, 4);
        test(1, 2, 2, 2, 1, 2, 4, 2, 6);
        test(1, 2, 0, 2, 1, 2, 4, 2, 0);
        System.out.println("All tests passed.");
    }
    

提交回复
热议问题