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

前端 未结 13 1010
小蘑菇
小蘑菇 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:12

    This problem can be solved with about 10 lines of Java code.

    You can start with an obvious but inefficient (O(N^2)) solution:

    public class Main {
    
        int solve(int[] array) {
            int answer = Integer.MAX_VALUE;
            for (int i = 3; i < array.length - 1; i++) {
                for (int j = 1; j < i - 1; j++) {
                    if (array[i] + array[j] < answer) {
                        answer = array[i] + array[j];
                    }
                }
            }
            return answer;
        }
    }
    

    But then you can notice that you actually do not need the internal for loop because you can just preserve the minimum and update it with every new element if necessary, which is faster than finding the minimum anew every time. Therefore the final O(N) solution looks like this:

    public class Main {
    
        int solve(int[] array) {
            int answer = Integer.MAX_VALUE;
            int min = array[1];
            for (int i = 3; i < array.length - 1; i++) {
                min = Math.min(min, array[i - 2]);
                if (array[i] + min < answer) {
                    answer = array[i] + min;
                }
            }
            return answer;
        }
    }
    

提交回复
热议问题