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

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

    I have used dynamic programming to solve it.

    Idea is to first create the array which tracks the minimum found till now as below: Input array = [1, 3, 0, 5, 6] Minimum array = [1, 1, 0, 0, 0]

    Now using the minimum array and the input array we can use below:

    DP[i] = min(DP[i-1], min(first_data, second_data))
    

    where DP[i] means the minimum found till now which is sum of two previous alternate elements.

    first_data = sum of current element in input array + sum of current-2 element in minimum array

    second_data = sum of current-1 element in input array + sum of current-3 element in minimum array

        import random
        def get_min(numbers):
                #disregard the first and last element
                numbers = numbers[1:len(numbers)-1]
                #for remembering the past results
                DP = [0]*len(numbers)
                #for keeping track of minimum till now found
                table = [0]*len(numbers)
                high_number = 1 << 30
    
                min_number = numbers[0]
                table[0] = min_number
                for i in range(0, len(numbers)):
                        DP[i] = high_number
                for i in range(1, len(numbers)):
                        if numbers[i] < min_number:
                                min_number = numbers[i]
                                table[i] = numbers[i]
                        else:
                                table[i] = min_number
                for i in range(0, len(numbers)):
                        min_first, min_second = high_number, high_number
                        if i >= 2:
                                min_first = numbers[i] + table[i-2]
                        if i >= 3:
                                min_second = numbers[i-1] + table[i-3]
                        if i >= 1:
                                DP[i] = min(min(DP[i-1], min_first), min_second)
                return DP[len(numbers)-1]
    
        input = random.sample(range(100), 10)
        print(input)
        print(get_min(input))
    

提交回复
热议问题