Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs/algorithms/algs/008/ #25

Open
utterances-bot opened this issue Dec 13, 2021 · 2 comments
Open

docs/algorithms/algs/008/ #25

utterances-bot opened this issue Dec 13, 2021 · 2 comments

Comments

@utterances-bot
Copy link

第 008 期(2021.12.02) | Learning

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

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

Copy link

看着可以用动态规划来做

Copy link

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants