1 Star 1 Fork 0

laodasbch/Leetcode-Complete-Guide

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
198.txt 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
JunB(66哥) 提交于 5年前 . Update 198.txt
思路:
1. 用最大堆来maintain
2. 这样可以找出前面最大的那个同时我们要注意他们是不是连续的
代码:
class Solution {
public int rob(int[] A) {
if(A.length==0)return 0;
PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->{
return b[0]-a[0];
});
for(int i=0;i<A.length;i++){
int cur=A[i];
if(pq.size()==0){
pq.add(new int[]{cur,i});
}
else if(pq.size()==1){
int top[]=pq.peek();
if(i-top[1]==1){
pq.add(new int[]{cur,i});
}else{
pq.add(new int[]{cur+top[0],i});
}
}else{
int one[]=pq.poll();
int two[]=pq.peek();
if(i-one[1]==1){
pq.add(new int[]{cur+two[0],i});
}else{
pq.add(new int[]{cur+one[0],i});
}
pq.add(one);
}
}
return pq.peek()[0];
}
}
o(n) 解法
class Solution {
public int rob(int[] A) {
int dp[]=new int[A.length];
int res=0;
for(int i=0;i<A.length;i++){
dp[i]=Math.max(get(dp,i-1),A[i]+get(dp,i-2));
res=Math.max(res,dp[i]);
}
return res;
}
public int get(int A[],int i){
if(i<0)return 0;
return A[i];
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/laodasbch/Leetcode-Complete-Guide.git
git@gitee.com:laodasbch/Leetcode-Complete-Guide.git
laodasbch
Leetcode-Complete-Guide
Leetcode-Complete-Guide
master

搜索帮助