題意:
假如你是一個(gè)搶劫犯,在某天夜里搶劫一排挨著的房屋丰捷,但是不能搶劫相鄰的房屋坯墨,請(qǐng)問能得到最多多少現(xiàn)金。每間房屋的存款順序放在一個(gè)一維數(shù)組value[]中病往。
思路:
這道題一看就是一道DP問題捣染。分兩種情況,當(dāng)前房屋被搶劫和不被搶劫停巷。
被搶劫時(shí)耍攘,前一個(gè)房屋不被搶劫,rob = norob + value[i];
不被搶劫時(shí)畔勤,前一個(gè)房屋存在可能被搶劫也可能不被搶劫蕾各,但是這里應(yīng)該取其中最大值的norob = max(rob,norob);
按順序循環(huán)遍歷每個(gè)房屋,直到最后一個(gè)房屋庆揪,返回當(dāng)前max(rob式曲,norob)。
public class HouseRobber {
public static int rob(int[] nums) {
int rob = 0;
int norob = 0;
int temrob = 0;
for(int i= 0; i < nums.length; i++){
temrob = norob + nums[i];
norob = Math.max(norob, rob);
rob = temrob;
}
return Math.max(rob, norob);
}
public static void main(String args[]){
int []value = {1,2,3,4,5,6,7,8,9,10};
System.out.println(HouseRobber.rob(value));
}
}