我在leetcode上浏览解决方案,并在HouseRobber 1中找到了这个:
last, now = 0, 0
for i in nums:
last, now = now, max(last + i, now)
return now
我对代码本身如何以最大值执行感到困惑。这对我来说有点模棱两可,因为我还不熟悉python并且来自C ++,我写了这样的东西:
lastNum = 0 #last number we took in
lastSpot = 0 #last spot we took the number from (index placeholder)
totalSum = 0 #max amount we can take from the houses
for i, element in enumerate(nums):
if element > lastNum: #if our element is bigger than our last number, we check...
if lastSpot != i - 1: #if our last spot was more than a space away AND our element is bigger, we take our index number.
if lastNum + nums[lastSpot] < lastNum + nums[i]:
lastNum = element
totalSum += element
lastSpot = i #update our last spot
elif lastSpot == i - 1: #if our last spot is next to our current spot, we gotta' swap a few values now.
totalSum -= lastNum #we remove the last value we added since we found a bigger spot
totalSum += element
lastSpot = i
lastNum = element
elif i == lastSpot + 2: #if we are more than one spot away from our last spot, we take the number anyway and add it.
lastNum = element
totalSum += element
elif element < lastNum:
if lastNum + nums[lastSpot] < lastNum + nums[i]:
lastNum = element
totalSum += element
totalSum += nums[i - 2]
lastSpot = i
else:
lastNum = element
return totalSum
我知道我们需要相互验证这些值,如果我们传递一个值,我们会检查它是否大于我们上次持有的值加上我们的当前值,然后决定跳过或取决于如果它是我们当前选择的值旁边的一个位置。但是如何在一小段python代码中执行呢?我知道max函数如何获取2个值并返回两个中较大的值 - 但我错过了什么?难道这也不会返回相同值旁边的值吗?谢谢你的时间!
答案 0 :(得分:1)
在每个迭代的代码中,如下所示:
temp = last
last = now
now = max(temp + i, now)
所以c ++中的这段代码实际上是这样的:
last = 0;
now = 0;
for (int i = 0; i < num.length; i++) {
temp = last;
last = now;
now = max(temp + nums[i], now);
}