Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9af2fd1

Browse files
author
hasibulislam999
committed
Guess Number Higher or Lower II problem solved
1 parent 2bb05ec commit 9af2fd1

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* Title: Guess Number Higher or Lower II
3+
* Description: Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
4+
* Author: Hasibul Islam
5+
* Date: 06/05/2023
6+
*/
7+
8+
/**
9+
* @param {number} n
10+
* @return {number}
11+
*/
12+
var getMoneyAmount = function (n) {
13+
// Memo
14+
this.memo = new Map();
15+
16+
return dp(n, 0, n);
17+
};
18+
19+
var dp = function (n, start, end) {
20+
let key = `${start}_${end}`;
21+
22+
// Base, there is only 1 node on this side of the leg, which mean our guess is always correct and it cost nothing so return 0
23+
if (end - start < 2) {
24+
return 0;
25+
}
26+
27+
// Base, there are only 2 nodes on this side of the leg, which mean we only need to pick cheapest guess
28+
if (end - start === 2) {
29+
// The `start` will always be smaller so pick `start`, add 1 to account for 0 index
30+
return start + 1;
31+
}
32+
33+
// Return from memo
34+
if (this.memo.has(key) === true) {
35+
return this.memo.get(key);
36+
}
37+
38+
// Minimum cost
39+
let minCost = Infinity;
40+
41+
// Try to arrange the tree's left and right leg and find the cost of each leg
42+
for (let i = start; i < end; i++) {
43+
let left = dp(n, start, i);
44+
let right = dp(n, i + 1, end);
45+
46+
// Cost of current guess, add 1 to account for 0 index
47+
let curr = i + 1;
48+
49+
// Update cost of current guess, which is the max of left or right leg
50+
curr = Math.max(left + curr, right + curr);
51+
52+
// Then update the minimum cost for entire tree
53+
minCost = Math.min(minCost, curr);
54+
}
55+
56+
// Set memo
57+
this.memo.set(key, minCost);
58+
59+
return minCost;
60+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /