LeetCode 213: House Robber II
2016-05-26 14:58
405 查看
LeetCode 213: House Robber II
思路
在House Robber题的基础上分两种情况:nums[0]未被打劫;
nums[0]被打劫;
代码
public class Solution { public int rob(int[] nums) { int length = nums.length; if (length == 0) return 0; if (length == 1) return nums[0]; if (length == 2) return nums[0] > nums[1] ? nums[0] : nums[1]; //first case nums[0] is robbed int first = nums[0], second = nums[0]; for (int i = 2; i < nums.length - 1; i++) { int tmp = (first + nums[i]) > second ? (first + nums[i]) : second; first = second; second = tmp; } int ret = second; //first case nums[0] is not robbed first = 0; second = nums[1]; for (int i = 2; i < nums.length; i++) { int tmp = (first + nums[i]) > second ? (first + nums[i]) : second; first = second; second = tmp; } return ret > second ? ret : second; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解