Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Iterative Solution
- *
- * Refer:
- * https://leetcode.com/problems/house-robber-ii/discuss/59934/Simple-AC-solution-in-Java-in-O(n)-with-explanation/61023
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- *
- * N = Length of the input nums array.
- */
- class Solution {
- public int rob(int[] nums) {
- if (nums == null || nums.length == 0) {
- return 0;
- }
- int len = nums.length;
- if (len == 1) {
- return nums[0];
- }
- return Math.max(nums[0] + robHelper(nums, 2, len - 2), robHelper(nums, 1, len - 1));
- }
- private int robHelper(int[] nums, int left, int right) {
- int previousMax = 0;
- int currentMax = 0;
- for (int i = left; i <= right; i++) {
- int temp = currentMax;
- currentMax = Math.max(currentMax, nums[i] + previousMax);
- previousMax = temp;
- }
- return currentMax;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement