![](/img/trans.png)
[英]How to swap members of two arrays so that the difference of sum of the elements of both arrays be minimum?
[英]How to pick elements from both arrays so that the difference between the sum is the minimum
有 2 個 arrays,其中兩個 arrays 的長度相同。
數組 A = 一組非負整數
數組 B = 一組非正整數
對於每個索引 i,我必須要么 select A[i] 要么 B[i] 並且想知道 abs(sum) 的最小值。
例如
示例 1
A = {1,2,3,4},B = {-1,-2,-3,-4}
那么通過選擇 1、-2、-3 和 4,abs(sum) 的最小值將為 0。(-1、2、3、-4)也可以。
示例 2
A = {1,1,1,3},B = {0,0,0,-3}
那么通過選擇 1,1,1 和 -3,abs(sum) 的最小值將為 0。
我只能想到一種天真的方法來計算需要指數時間的所有可能組合。 有沒有更好的方法來解決這個問題?
這可以在O(n * num_diffs)
時間復雜度內完成,方法是想象負數桶只是我們試圖盡可能接近另一個正數桶的另一個正數桶。
JavaScript 代碼( diff
是放置一個桶時產生的差異):
function f(A, B){ let diffs = new Set(); diffs.add(A[0]); diffs.add(-B[0]); for (let i=1; i<A.length; i++){ let newDiffs = new Set(); for (d of [...diffs]){ newDiffs.add(d + A[i]); newDiffs.add(Math.abs(d + B[i])); } diffs = newDiffs; } console.log(`Diffs: ${ [...diffs] }`); return Math.min(...diffs); } var ABs = [ [[1, 2, 3, 4], [-1, -2, -3, -4]], // 0 [[1, 1, 1, 3], [0, 0, 0, -3]] // 0 ] for (let [A, B] of ABs){ console.log(`A: ${ A }`); console.log(`B: ${ B }`); console.log(`Result: ${ f(A, B) }`); console.log(''); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.