From 116dd2a75153f0f95b9baf6eeab0aace04ec6580 Mon Sep 17 00:00:00 2001 From: aadil42 <77232799+aadil42@users.noreply.github.com> Date: Tue, 15 Aug 2023 18:50:57 +0530 Subject: [PATCH] Create code.js Adding solution to delete-and-earn in js. Submission Link: https://leetcode.com/problems/delete-and-earn/submissions/1022078541/ --- .../010. Delete and Earn/code.js | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 02. Algorithms/09. Dynamic Programming/010. Delete and Earn/code.js diff --git a/02. Algorithms/09. Dynamic Programming/010. Delete and Earn/code.js b/02. Algorithms/09. Dynamic Programming/010. Delete and Earn/code.js new file mode 100644 index 00000000..161cf542 --- /dev/null +++ b/02. Algorithms/09. Dynamic Programming/010. Delete and Earn/code.js @@ -0,0 +1,48 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var deleteAndEarn = function(nums) { + const hash = new Map(); + + nums.forEach((num) => { + const numCache = hash.get(num); + if(numCache) { + hash.set(num, numCache + 1); + } else { + hash.set(num, 1); + } + }); + + const uniqueNums = new Set(); + + nums.forEach((num) => { + uniqueNums.add(num); + }); + + nums = [...uniqueNums]; + + nums.sort((a,b) => { + return a-b; + }); + + let earn1 = 0; + let earn2 = 0; + + for(let i = 0; i < nums.length; i++) { + const currentEarn = nums[i] * hash.get(nums[i]); + + if(nums[i] === nums[i-1] + 1) { + const temp = earn2; + earn2 = Math.max(earn2, currentEarn + earn1); + earn1 = temp; + } else { + const temp = earn2; + earn2 = currentEarn + earn2; + earn1 = temp; + } + } + + return earn2; + +};