House Robber 2 Leetcode problem giving incorrect output - javascript

I am solving the Leetcode problem House Robber II. The problem says,
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. The constraint is you can not rob two adjacent houses. Also, the houses in that place are arranged in a circle, so the first and last houses are also adjacent.
Here is the link: https://leetcode.com/problems/house-robber-ii/
I have used the top-down approach to solve it. This is function definition: dp(index, isFirstHouseRobbed) In the function body, I am checking if(index === nums.length - 1 && isFirstHouseRobbed === true) return 0;. Here is the complete function:
var rob = function(nums) {
const dp = (index, isFirstHouseRobbed) => {
if (index >= nums.length) {
return 0;
}
if (index === nums.length - 1 && isFirstHouseRobbed === true) {
return 0;
}
if (index === 0) {
// Two choice: rob or not rob
// rob
let max1 = dp(index + 2, true) + nums[index];
// not rob
let max2 = dp(index + 1, false);
return Math.max(max1, max2);
} else {
// Two choice: rob or not rob
// rob
let max1 = dp(index + 2, false) + nums[index]; // This does not work
// --->(line 20) let max1 = dp(index + 2, isFirstHouseRobbed) + nums[index]; // But this works.
// not rob
let max2 = dp(index + 1, false); // This does not work
// --->(line23) let max2 = dp(index + 1, isFirstHouseRobbed); // But This works.
return Math.max(max1, max2);
}
}
return dp(0, false);
};
This solution works only if I use line20 and line23. The only difference between those two lines and their previous lines is I am using the variable isFirstHouseRobbed instead of passing false. My question is, in the main function call I am calling dp(0, false). So, the value of isFirstHouseRobbed should be set to false. My question is, why using false instead of isFirstHouseRobbed not working, where the value of isFirstHouseRobbed is set to false anyway. Maybe I am missing something easy, but could not figure it out. Any help would be greatly appreciated.

It's not always false; one of your recursive cases passes true for the second parameter. This makes sense — there wouldn't be much point in having it be a parameter if it never changed.

Related

What am I missing in my approach to this Dynamic Programming problem? (Leetcode 740. Delete and Earn)

I'm trying to understand how to solve Leetcode Problem #740: Delete and Earn
I recently was given this problem as part of a pre-interview assessment and was unable to complete it in the allotted time. I've been working on it today to try and wrap my head around it, but I'm kinda spinning in circles at the moment. I've checked numerous resources, videos, tutorials, etc, but I'm working in vanilla JS and a lot of the guides are in C++, Python, or Typescript which I don't currently know. (I plan on learning Python and Typescript at minimum, but I'm working with my current set of knowledge for the time being). This is leading to confusion and frustration, as an accurate translation of sample python/c++ code, etc continues to elude me.
The problem is as follows:
You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:
Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.
Return the maximum number of points you can earn by applying the above operation some number of times.
Example 1
Input: nums = [3,4,2]
Output: 6
Explanation: You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].
- Delete 2 to earn 2 points. nums = [].
You earn a total of 6 points.
Example 2
Input: nums = [2,2,3,3,3,4]
Output: 9
Explanation: You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].
- Delete a 3 again to earn 3 points. nums = [3].
- Delete a 3 once more to earn 3 points. nums = [].
You earn a total of 9 points.
What I have so far:
const deleteAndEarn = (nums) => {
if(!nums || nums.length === 0) return 0;
if(nums.length === 1) return nums[0];
if(nums.length === 2) return nums[1];
const freq = makeDict(nums);
let prevNum
let [keep, avoid] = [0, 0];
for(const num of [...Object.keys(freq)].sort()){
let max = Math.max(keep, avoid)
if(parseInt(num) - 1 !== prevNum){
[keep, avoid] = [
(freq[num] * parseInt(num)) + max,
max
]
}else{
[keep, avoid] = [
parseInt(num) * freq[num] + avoid,
max
]
}
prevNum = parseInt(num)
}
return Math.max(keep, avoid)
};
const makeDict = (nums) => {
const dict = {}
for(const num of nums){
dict[num] = !!dict[num] ? dict[num]++ : 1
}
return dict
}
Provided Python Solution
This is what I've tried to model my code off of, but I don't actually know Python syntax so I'm sure I'm missing something.
class Solution(object):
def deleteAndEarn(self, nums):
count = collections.Counter(nums)
prev = None
avoid = using = 0
for k in sorted(count):
if k - 1 != prev:
avoid, using = max(avoid, using), k * count[k] + max(avoid, using)
else:
avoid, using = max(avoid, using), k * count[k] + avoid
prev = k
return max(avoid, using)
I really don't understand at all why this code isn't working, and I've even gone as far as to run sample cases step by step. Please help me understand how to do this so I can get a job!
Many thanks
I figured it out! The problem is twofold.
Bug Number One
First, shoutout to David Eisenstat for catching the bug in my makeDict() function.
The incorrect line of code reads:
dict[num] = !!dict[num] ? dict[num]++ : 1
Whereas the correct syntax is as follows:
dict[num] = !!dict[num] ? ++dict[num] : 1
or alternatively
dict[num] = !!dict[num] ? dict[num] + 1 : 1
The issue comes from how postfix vs prefix increment operators work in Javascript.
From the MDN docs:
If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.
Bug Number Two
The second issue comes from my initial guard clauses.
if(nums.length === 2) return nums[1];
I think this was a remnant from when I was sorting the provided array at the very start, but even then automatically selecting the last element doesn't really make any sense. I deleted this line and, combined with the adjustment to the previous makeDict() function, the code passed all the provided tests.
My working solution is provided below. Open to any suggestions as to how to improve the code for both readability, or efficiency.
Appreciate the help!
const deleteAndEarn = (nums) => {
if(!nums || nums.length === 0) return 0;
if(nums.length === 1) return nums[0];
const freq = makeDict(nums);
let prevNum
let [keep, avoid] = [0, 0];
for(const num of Object.keys(freq)){
let max = Math.max(keep, avoid)
if(parseInt(num) - 1 !== prevNum){
[keep, avoid] = [
(freq[num] * parseInt(num)) + max,
max
]
}else{
[keep, avoid] = [
parseInt(num) * freq[num] + avoid,
max
]
}
prevNum = parseInt(num)
}
return Math.max(keep, avoid)
};
const makeDict = (nums) => {
const dict = {}
for(const num of nums){
dict[num] = !!dict[num] ? ++dict[num] : 1
}
return dict
}
One bug in your existing code is that
[...Object.keys(freq)].sort()
will not sort numbers in order - see here.
Another bug is that your algorithm doesn't have any backtracking - you don't want to greedily choose 3 when given [3, 4, 4, 4].
I think the best way to approach this is to understand that it's only strings of consecutive numbers in the input that need to be considered. For example, given
[1, 2, 3, 6, 7, 8]
Separate it out into all the consecutive strings of integers:
[1, 2, 3]
[6, 7, 8]
Then decide the optimal picks for each sequence.
You can't just pick all odd numbers or all even numbers in the sequence, because that would fail to pick, eg, 1 and 4 for [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4]. The best approach I can see is to use a recursive function: when checking a sequence, getBestSequenceSum, starting with N, return the maximum of:
Sum of N plus getBestSequenceSum(seq.slice(2)) (skipping the next item in the sequence), OR
Sum of getBestSequenceSum(seq.slice(1)) (using the next item in the sequence)
to adequately cover all possibilities.
There may be more efficient algorithms, but this is relatively simple and intuitive.
const getBestSequenceSum = (seq) => {
if (seq.length === 0) return 0;
// Include the lowest value in the sequence, or not?
const sumOfLowestVal = seq[0].num * seq[0].count;
return Math.max(
sumOfLowestVal + getBestSequenceSum(seq.slice(2)),
getBestSequenceSum(seq.slice(1))
);
};
const deleteAndEarn = (nums) => {
nums.sort((a, b) => a - b);
let lastNum;
const sequences = [];
for (const num of nums) {
if (num !== lastNum && num !== lastNum + 1) {
// New sequence
sequences.push([]);
}
const thisSequence = sequences[sequences.length - 1];
if (num !== lastNum) {
thisSequence.push({ num, count: 0 });
}
thisSequence[thisSequence.length - 1].count++;
lastNum = num;
}
return sequences.reduce((a, seq) => a + getBestSequenceSum(seq), 0);
};
console.log(deleteAndEarn([10,8,4,2,1,3,4,8,2,9,10,4,8,5,9,1,5,1,6,8,1,1,6,7,8,9,1,7,6,8,4,5,4,1,5,9,8,6,10,6,4,3,8,4,10,8,8,10,6,4,4,4,9,6,9,10,7,1,5,3,4,4,8,1,1,2,1,4,1,1,4,9,4,7,1,5,1,10,3,5,10,3,10,2,1,10,4,1,1,4,1,2,10,9,7,10,1,2,7,5]));
The number of calculations could be reduced somewhat by changing the { num, count: 0 } objects to a single number instead, but that would be more difficult to understand when reading the code.
You could also reduce the number of calculations by caching already-optimized sequences so as not to recalculate them multiple times, but that'd make the code significantly longer.

Why does my code work in one environment, but not in another?

I'm doing a kata on Codewars. I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(i.e. [1, 2, 4] should return 0). I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test. What is going wrong here?
I've tried testing with console.logs, and my solution holds. I know I could just use filter to solve the problem, but i wan't to practice fundamentals.
let odd = [];
let even = [];
function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
function iqTest(numbers) {
let nums = numbers.split(' ').map(function(item) {
return parseInt(item, 10);
})
for (let i in nums) {
if (isEven(nums[i])) {
even.push(nums[i])
} else {
odd.push(nums[i])
}
}
if (even.length > odd.length) {
return nums.indexOf(odd[0]) + 1;
} else {
return nums.indexOf(even[0]) + 1;
}
}
The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1.
You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.
No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.
For a faster return value store the index instead of the value and omit a later indexOf seach.
function isEven(i) { return i % 2 === 0; }
function iqTest(numbers) {
var even = [], odd = [], values = numbers.split(' ');
for (let i = 0; i < values.length; i++) {
(isEven(values[i]) ? even : odd).push(i);
if (even.length && odd.length && even.length + odd.length > 2)
return (even.length < odd.length ? even : odd)[0] + 1;
}
}
console.log(iqTest("1 2 4")); // 1
console.log(iqTest("2 4 7 8 10")) // 3
console.log(iqTest("1 2 1 1")); // 2

Javascript Time Complexity Analysis

Hi there I have been researching and trying to learn how to check for the time complexity of certain algorithms. I've seen this video which was very helpful.
That being said I wondered off and started trying to work out the Worsts Case and an average case of certain algorithms.
1
I believe in the following snippet it is O(n) since to ind the value for sin we have to loop the entire array.
function mySin(x, iterNum) {
var mxx = -x*x;
var sin = 1;
var n = 0;
var term = 1;
for (var i = 1; i <= 2*iterNum; i++) {
n = n + 2;
term = term * mxx / ( n*(n+1) );
sin = sin + term
}
sin = x*sin;
console.log(sin + " = my function.");
console.log(Math.sin(x) + " math.sin");
}
Thanks again
2
function calculateFibonacciSum (num) {
if(cachedNumbers[num]) {
return cachedNumbers[num];
}
if(('number' === typeof num) && num <= 0) {
throw new Error ('Fibonnci series starts with 0. Please, enter any interget greater than or equal to 0');
}
else if(('number' === typeof num) && num === 0) {
return 0;
}
else if(('number' === typeof num) && (num === 1 || num === 2)) {
return 1;
}
else {
var value = calculateFibonacciSum(num-1) + calculateFibonacciSum(num-2);
cachedNumbers[num] = value;
return value;
}
}
While for this one I think it is also O(n) since in the first if/else statement the tc is O(1) since its contestant whilst the final else statement we must loop all the numbers and if the number is not calculated then call the function again (aka recurssion).
TIA
Both of these seem correct to me. Here's a bit more explanation:
1.
This is in fact O(n), as there are n iterations of the loop, the rest constant time; and n is proportional to iterNum
2.
This one is also linear time, but only since you cache the results of previous calculations. Otherwise it would be O(2n).
It is linear time since it essentially runs a loop down to the base cases (0 and 1). In fact, you could re-write this one using a loop instead of recursion.

Algorithm that involves rounding and multiples

So I have a problem where I have an array of some length (usually long). I have an initial start index into that array and a skip value. So, if I have this:
var initial = 5;
var skip = 10;
Then I'd iterate over my array with indexes 5, 15, 25, 35, etc.
But then I may get a new start value and I need to find the closest value to the initial plus or minus a multiple of the skip and then start my skip. So if my new value is 23 then I'd iterate 25, 35, 45, etc.
The algorithm I have for this is:
index = (round((start - initial) / skip) * skip) + initial
And then I need a check to see if index has dropped below zero:
while(index < 0) index += skip;
So my first question is if there's a name for this? A multiple with random start?
My second question is if there's a better way? I don't think what I have is terribly complicated but if I'm missing something I'd like to know about it.
If it matters I'm using javascript.
Thanks!
Edit
Instead of
while(index < 0) index += skip;
if we assume that both initial and skip are positive you can use:
if (index < 0) index = initial % skip;
To get the closest multiple of a number to a test number: See if the modulo of your test number is greater than number/2 and if so, return number - modulo:
function closestMultiple(multipleTest,number)
{
var modulo = multipleTest%number;
if(0 == modulo )
{
return multipleTest;
}
else
{
var halfNumber = number/2;
if(modulo >= halfNumber)
{
return multipleTest + (number-modulo);
}
else
{
return multipleTest - modulo;
}
}
}
To check if a number is a multiple of another then compare their modulo to 0:
function isMultiple(multipleTest,number)
{
return 0 == multipleTest%number;
}
You might want to add some validations for 0 in case you expect any inside closestMultiple.
The value of index computed as you put it
index = round((start - initial)/skip) * skip + initial
is indeed the one that minimizes the distance between the sequence with general term
aj = j * skip + initial
and start.
Therefore, index can only be negative if start lies to the left of
(a-1 + a0)/2 = initial - skip/2
in other words, if
start < initial - skip/2.
So, only in that case you have to redefine index to 0. In pseudo code:
IF (start < (initial - skip/2))
index = 0
ELSE
index = round((start - initial)/skip) * skip + initial
Alternatively, you could do
index = round((start - initial)/skip) * skip + initial
IF index < 0 THEN index = 0
which is the same.
No while loop required:
function newNum(newstart, initial, skip) {
var xLow = newstart + Math.abs(newstart - initial) % skip;
var xHi = newstart + skip;
var result = (xLow + xHi) / 2 > newstart ? xLow : xHi;
if (result < 0) result += skip;
return result;
}
Take the distance between your new starting point and your initial value, and find out what the remainder would be if you marched towards that initial value (Modulus gives us that). Then you just need to find out if the closest spot is before or after the starting point (I did this be comparing the midpoint of the low and high values to the starting point).
Test:
newNum(1, 20, 7) = 6
newNum(-1, 20, 7) = 6
newNum(180, 10, 3) = 182
(Even though you stated in your comments that the range of the new starting point is within the array bounds, notice that it doesn't really matter).

Using recursion to search all combinations of elements in an array of integers

I am working on this problem from Coderbyte using JS:
Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.
The problem seems ripe for a recursive solution, given the branching nature of the need to explore the various combinations of array elements. I would also like to use recursion to get some extra practice.. I'm still very new to coding.
Here is the solution I came up with, and I was very happy about it until I started testing and discovered that it is not at all a solution:
function ArrayAdditionI(arr) {
// sorting the array to easily remove the biggest value
var sArr = arr.sort(function (a, b) {
return a-b;});
// removing the biggest value
var biggest = sArr.pop();
// count will be iterated to stop the recursion after the final element of the array has been processed
var count = 0;
function recursion (start, i) {
if (sArr[i] + start === biggest) {
return true;
}
else if (start + sArr[i] < biggest) {
return recursion(start + sArr[i], i+1);
}
else if (start + sArr[i] > biggest && count < sArr.length) {
count++;
return recursion(0, count);
}
else {
return false;
}
}
return recursion(0,0);
}
This code works only if the array elements which can be summed to fulfill the base case are adjacent to each other; calling ArrayAdditionI([1,2,3,4]), for example, will not work because the two elements which must be summed to reach the target value("1" in position 0, and "3" in position 2) are not adjacent.
My flow will return 1, then 1+2, then 1+2+3, then 2, then 2+3, then 3, and finally return false since the target (4) was not reached.
I can visualize how a proper solution needs to flow through a given array, but I don't know how to make this happen through recursion. For the given array [1,2,3,4], the flow should check results in this pattern: (position0, pos0+pos1, pos0+pos2, pos0+pos1+pos2, pos2, pos2+pos3, pos3). Can anyone give me a nudge? I'm going to think on this more before I sleep in an hour and give it a fresh go in the morning.. maybe my brain just needs a recharge.
Again, I'm really new to this, if I've made some very silly mistakes please let me know, I'll learn from them. Thanks!
Your algorithm has a flaw. Your function looks only one step forward.
You need to add loop inside to look over all rest values.
function ArrayAdditionI(arr) {
// sorting the array to easily remove the biggest value
// slice added to prevent original array modification
var sArr = arr.slice().sort(function (a, b) {
return a - b;
});
// removing the biggest value
var biggest = sArr.pop();
function recursion(start, i) {
var result = false;
// looking over all rest values of array
for (var j = i; j < sArr.length && !result; j++) {
if (sArr[j] + start === biggest) {
result = true;
}
else if (start + sArr[j] < biggest) {
result = recursion(start + sArr[j], j + 1);
}
}
return result;
}
return recursion(0, 0);
}
function ArrayAdditionI (arr) {
var sArr = arr.sort(function (a,b) {
return a-b;
});
var biggest = sArr.pop();
function recursion (start, indx) {
if (start + sArr[indx] === biggest) {
return true;
}
else if (sArr.length < indx) {
return false;
}
else if (start + sArr[indx] < biggest) {
return recursion(start + sArr[indx], indx + 1) || recursion(start, indx+1)
}
else {
return false;
}
}
return recursion(0,0);
}

Categories