最大相邻乘积和(面试题)

时间:2021-05-10 19:04:53

标签: arrays algorithm optimization dynamic-programming

我们有一个整数数组,其中每个位置的整数被视为其值。每次选择一个职位时,您将获得与其相关的金额乘以其相邻职位的价值(左侧和右侧)。选择一个位置后,它将从数组中删除,其左右位置将变得彼此相邻。

如果没有相邻位置,则假设相同的值为 1。例如,如果只剩下一个位置并且您选择它,那么它的值将乘以 1 作为左右相邻位置。

找出在选择所有职位后最后可以赚取的最大金额。

我已经使用以下递归关系对其实施了动态编程方法:首先我们观察到,如果我们在上述过程中以某种方式遇到了一个步骤,其中我们将 arr[position_p]arr[position_q] 相乘,那么 position_p 和 position_q 之间的所有位置都应该已经被选中了。
为简单起见,让我们假设数组索引从 1 开始,位置 0 和位置 n+1 根据问题包含值 1,其中 n 是数组中的元素数。 所以我们需要按照数量最大化的顺序选择位置 p+1 到 q-1。

使用这个,我们得到递推关系:
如果 f(p,q) 是仅从位置 p+1 到 q-1 中选择获得的最大数量,那么我们有:
f(p, q) = max ( f(p,k) + f(k,q) + arr[p] * arr[k] * arr[q] ) for k between p and q (Excluding p and q) 其中 k 是在选择 p 或 q 之前从位置 p+1 到 q-1 中选择的最后一个位置

这是 python 实现:

import numpy as np 

n = int(input("Enter the no. of inputs : "))

arr = [1]
arr = arr + list( map( int, input("Enter the list : ").split() ) ) 
arr.append(1)

# matrix created to memoize values instead of recomputing
mat = np.zeros( (n+2, n+2), dtype = "i8" )

# Bottom-up dynamic programming approach
for row in range ( n + 1, -1, -1 ) :

    for column in range ( row + 2, n + 2 ) :

        # This initialization to zero may not work when there are negative integers in the list.
        max_sum = 0

        # Recurrence relation 
        # mat[row][column] should have the maximmum product sum from indices row+1 until column-1
        # And arr[row] and arr[column] are boundary values for sub_array 
        # By above notation, if column <= row + 1, then there would be no elements between them and thus mat[row][column] should remain zero

        for k in range ( row + 1 , column ) :

            max_sum = max( max_sum, mat[row][k] + mat[k][column] + ( arr[row] * arr[k] * arr[column] ) )

        mat[row][column] = max_sum

print(mat[0][n+1])

问题是我在一段时间之前的编程面试中看到了以下问题。虽然我的解决方案似乎有效,但它的时间复杂度为 O(n^3) 和空间复杂度为 O(n^2)。 我能做得更好吗,当数组位置的所有值都是正的情况下(原始问题假设这一点)。并且对降低空间复杂性的任何帮助也表示赞赏。
谢谢你。

编辑: 虽然这不是证据,但正如@risingStark 所建议的,我在 LeetCode 上也看到了 same 问题,其中所有正确的算法似乎都使用了 O(n^2) 空间,在 O(n^3) 时间内运行案例解决方案。

0 个答案:

没有答案
相关问题