Skip to content

Instantly share code, notes, and snippets.

@antklim
Last active August 15, 2019 13:45
Show Gist options
  • Save antklim/e963fdd969d9048ca483d584a3f473fd to your computer and use it in GitHub Desktop.
Save antklim/e963fdd969d9048ca483d584a3f473fd to your computer and use it in GitHub Desktop.
const assert = require('assert')
/**
* Arrays have same length
* Array length within the range [0..200000]
* Number of frontend developers within the range [0..200000]
*
* @param Array - array of frontend contributions
* @param Array - array of backend contributions
* @param Number - number of frontend developers
*/
const solution = (A, B, F) => {
const backendCntribution = B.reduce((sum, item) => sum + item, 0)
if (F === 0) {
return backendCntribution
}
const arrayLength = A.length
// Indexes of chosen front end devs
const feIdxs = []
while (feIdxs.length < F) {
let bestScore = null
let bestIndex = null
for (let i = arrayLength; i--;) {
if (feIdxs.includes(i)) {
continue
}
let currentScore = backendCntribution - B[i] + A[i]
if (bestScore === null || currentScore > bestScore) {
bestScore = currentScore
bestIndex = i
}
}
feIdxs.push(bestIndex)
}
return feIdxs.reduce((sum, item) => sum - B[item] + A[item], backendCntribution)
}
const solution2 = (A, B, F) => {
const backendContribution = B.reduce((sum, item) => sum + item, 0)
if (F === 0) {
return backendContribution
}
const arrayLength = A.length
const diffs = []
for (let i = 0; i < arrayLength; i++) {
diffs[i] = [backendContribution - B[i] + A[i], i]
}
return diffs
.sort((a, b) => b[0] - a[0])
.slice(0, F)
.map(item => item[1])
.reduce((sum, item) => sum - B[item] + A[item], backendContribution)
}
assert.equal(solution2([4, 2, 1], [2, 5, 3], 2), 10)
assert.equal(solution2([7, 1, 4, 4], [5, 3, 4, 3], 2), 18)
assert.equal(solution2([5, 5, 5], [5, 5, 5], 1), 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment