From 00081154b28fbad90b6d4568cce73fc249cd1629 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Thu, 12 Jan 2023 10:59:31 -0800 Subject: [PATCH 1/2] solve 2144. Minimum Cost of Buying Candies With Discount --- ...um-cost-of-buying-candies-with-discount.js | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 2144.minimum-cost-of-buying-candies-with-discount.js diff --git a/2144.minimum-cost-of-buying-candies-with-discount.js b/2144.minimum-cost-of-buying-candies-with-discount.js new file mode 100644 index 00000000..23bf8532 --- /dev/null +++ b/2144.minimum-cost-of-buying-candies-with-discount.js @@ -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; \ No newline at end of file From 0113b36f001796ef3986e5697d762849a8d9f791 Mon Sep 17 00:00:00 2001 From: Hidemichi Shimura Date: Thu, 12 Jan 2023 11:00:03 -0800 Subject: [PATCH 2/2] test function minimumCost --- minimumCost.test.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 minimumCost.test.js diff --git a/minimumCost.test.js b/minimumCost.test.js new file mode 100644 index 00000000..7aa09b49 --- /dev/null +++ b/minimumCost.test.js @@ -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); +}); \ No newline at end of file