-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
066a842
commit f87f4a9
Showing
3 changed files
with
42 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
import { rob } from './rob'; | ||
|
||
describe('198. House Robber', () => { | ||
test('rob', () => { | ||
expect(rob([1, 2, 3, 1])).toBe(4); | ||
expect(rob([2, 7, 9, 3, 1])).toBe(12); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
type Rob = (nums: number[]) => number; | ||
|
||
/** | ||
* Accepted | ||
*/ | ||
export const rob: Rob = (nums) => { | ||
const n = nums.length; | ||
|
||
if (n === 0) return 0; | ||
if (n === 1) return nums[0]; | ||
|
||
let prev2 = 0; // This represents dp[i - 2] | ||
let prev1 = nums[0]; // This represents dp[i - 1] | ||
|
||
for (let i = 1; i < n; i++) { | ||
const current = Math.max(nums[i] + prev2, prev1); | ||
prev2 = prev1; | ||
prev1 = current; | ||
} | ||
|
||
return prev1; // prev1 now represents the max amount that can be robbed up to the last house | ||
}; |