diff --git a/Interview-Preparation-Kit/Greedy-Algorithms/luck-balance.js b/Interview-Preparation-Kit/Greedy-Algorithms/luck-balance.js new file mode 100644 index 0000000..dff1a4d --- /dev/null +++ b/Interview-Preparation-Kit/Greedy-Algorithms/luck-balance.js @@ -0,0 +1,29 @@ +/** + * @title Luck Balance + * @difficulty Easy + * @link https://www.hackerrank.com/challenges/luck-balance/problem + */ + +const luckBalance = (limit, contests) => { + const {length} = contests; + const sorted = contests.sort((a, b) => { + if (a[1] === b[1]) { + return b[0] - a[0]; + } + + return (a[1] > b[1]) ? 1 : -1; + }); + + let numImportant = length - [...sorted].findIndex(x => x[1] === 1); + numImportant = (numImportant > length) ? 0 : numImportant; + + const unImportant = [...sorted].slice(0, length - numImportant); + const loseImportant = [...sorted].slice(length - numImportant, length - numImportant + limit); + const winImportant = [...sorted].slice(length - numImportant + limit); + + const sumLuck = (unImportant.reduce((sum, [luck]) => sum + luck, 0) || 0) + + (loseImportant.reduce((sum, [luck]) => sum + luck, 0) || 0) - + (winImportant.reduce((sum, [luck]) => sum + luck, 0) || 0); + + return sumLuck; +}; diff --git a/README.md b/README.md index e1e1f85..546e179 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,13 @@ Generates the README.md. | --- | --- | --- | | Easy | [2D Array - DS](https://www.hackerrank.com/challenges/2d-array/problem) | [Solution](./Interview-Preparation-Kit/Arrays/2d-array-ds.js)| | Easy | [Left Rotation](https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem) | [Solution](./Interview-Preparation-Kit/Arrays/left-rotation.js)| +#### Greedy-Algorithms +| Difficulty | Problem | Solution | +| --- | --- | --- | +| Easy | [Luck Balance](https://www.hackerrank.com/challenges/luck-balance/problem) | [Solution](./Interview-Preparation-Kit/Greedy-Algorithms/luck-balance.js)| +#### Strings +| Difficulty | Problem | Solution | +| --- | --- | --- | #### Warm-up-Challenges | Difficulty | Problem | Solution | | --- | --- | --- |