台积电 OA 面试真题解析:Get Min Sum(线性方程最小项和)

20次阅读
没有评论

A linear equation of two variables is defined as a * x + b * y = z. For an array of integers arr and some query value z, the minimum sum solution is the minimum possible value of a + b where 0 <= a, 0 <= b, and a * arr[i] + b * arr[j] = z. It is possible that i = j.

Given two arrays of integers arr and query, and an integer k, for each value in query, replace z in the linear equation with query[x] and find the minimum sum solution. Return an answer array where each answer[x] is the answer to query[x]. If the sum of a + b is less than or equal to k, answer[x] is a + b. Otherwise, it is -1.

Example

arr = [1, 2, 3, 6, 67]
query = [1, 4, 30, 7, 88]
k = 5

Output:
[1, 2, 5, 2, -1]

For each query, choose non-negative integers a and b so that a * arr[i] + b * arr[j] = query[x] and minimize a + b. If no valid pair exists or the minimum sum exceeds k, return -1.

这题要求对每个查询值,判断是否能用数组中的两个数(允许同一个位置重复使用)表示成 a * arr[i] + b * arr[j] = query[x],并在 a、b 非负且 a + b 不超过 k 的前提下,找出最小的 a + b。核心思路是围绕查询值枚举可能的系数组合,再利用哈希表快速判断剩余部分是否能被数组中的某个值整除匹配;由于 k 很小,暴力枚举 a、b 的范围是可行的。实现时要特别注意:当 a 或 b 为 0 时的边界情况、无法表示时返回 -1、以及同一个元素可重复使用这一条件。

正文完
 0