learning icon indicating copy to clipboard operation
learning copied to clipboard

docs/algorithms/algs/008/

Open utterances-bot opened this issue 4 years ago • 2 comments

第 008 期(2021.12.02) | Learning

题目描述 # 一个专业的小偷,计划偷窃沿街的房屋。 每间房内都藏有一定的现金,影响小偷偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组 nums , 请计算不触动警报装置的情况下 ,一夜之内能够偷窃到的最

https://talkgo.dev/docs/algorithms/algs/008/

utterances-bot avatar Dec 13 '21 13:12 utterances-bot

看着可以用动态规划来做

supermario1990 avatar Dec 13 '21 13:12 supermario1990

func stealMaxMoney(nums []int) int {
	if len(nums) == 0 {
		return 0
	}
	if len(nums) == 1 {
		return nums[0]
	}
	if len(nums) == 2 {
		return max(nums[0], nums[1])
	}

	res := 0
	a := make([]int, len(nums))
	a[0] = nums[0]
	a[1] = max(a[0], a[1])
	for i := 2; i < len(nums); i++ {
		a[i] = max(a[i-2]+nums[i], a[i-1])
		if res < a[i] {
			res = a[i]
		}
	}
	return res
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

supermario1990 avatar Dec 13 '21 14:12 supermario1990