严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

House RobberI 高频题 其它公司也喜欢考

Go down

House RobberI 高频题 其它公司也喜欢考 Empty House RobberI 高频题 其它公司也喜欢考

Post by Admin Sat Oct 21, 2017 4:59 pm

public static int rob1(int[] num) {
if (num.length == 0) return 0;
int[] dp = new int[num.length + 1];
dp[0] = 0;
dp[1] = num[0];
for (int i = 2; i <= num.length; i++)dp[i] = Math.max(dp[i - 1], dp[i - 2] + num[i - 1]);
return dp[num.length];
}

public static int rob(int[] num){
if (num.length == 0) return 0;
int prepre = 0;
int pre = num[0];
for (int i = 1; i < num.length; i++) {
int cur = Math.max(prepre + num[i], pre);
prepre = pre;
pre = cur;
}
return pre;
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum