Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 2144.minimum-cost-of-buying-candies-with-discount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/* URL of this problem
* https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/description/
*
* @param {number[]} cost
* @return {number}
*/

var minimumCost = function(cost) {
// Create a copy of cost sorted in a descendign order
const SortedCost = [...cost].sort((a, b) => b - a);
let MinCost = 0;

while (SortedCost.length > 0) {
// Extract the current top 3 costs and add only the top 2 to MinCost
// The thrid cost becomes free by not being added to MinCost
const Candies = SortedCost.splice(0, 3);
const FirstCandie = Candies[0] ?? 0;
const SecondCandie = Candies[1] ?? 0;

MinCost += FirstCandie + SecondCandie;
}

return MinCost;
};

module.exports = minimumCost;
29 changes: 29 additions & 0 deletions minimumCost.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const minimumCost = require("../jest-test/2144. minimum-cost-of-buying-candies-with-discount");

test("Return the minimum cost of buying all the candies", () => {
expect(minimumCost([6,5,7,9,2,2])).toBe(23);
});

test("Return the sum of the element values if the input cost has only 2 elements", () => {
expect(minimumCost([1,2])).toBe(3);
});

test("Return the element value if the input cost has only 1 element", () => {
expect(minimumCost([1])).toBe(1);
});

test("Return 0 if the input cost has no element", () => {
expect(minimumCost([])).toBe(0);
});

test("Return Infinity if the input cost has Infinity", () => {
expect(minimumCost([6,5,7,9,2,2,Infinity])).toBe(Infinity);
});

test("Return -Infinity if the input cost has -Infinity and it does not become free for a third candy", () => {
expect(minimumCost([6,5,7,9,2,2,-Infinity])).toBe(-Infinity);
});

test("Return -Infinity if the input cost has -Infinity but it becomes free for a third candy", () => {
expect(minimumCost([6,5,7,9,2,-Infinity])).toBe(23);
});