iT邦幫忙

2021 iThome 鐵人賽

DAY 21
1
AI & Data

機器學習與前端網頁系列 第 21

Day 21 LeetCode 198. House Robber

  • 分享至 

  • xImage
  •  

當想不到今天要做什麼時就來解 LeetCode。

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.nums

Example 1:

Input: nums = [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.

Example 2:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 3:

Input: nums = [1,2,3]
Output: 3

from typing import List

class Solution:

    def solve(self, nums: List[int]) -> int:

        bag = [0] * (len(nums))

        bag[0] = nums[0]
        bag[1] = max(nums[0], nums[1])
        for i in range(2, len(nums)):
            bag[i] = max(bag[i-2] + nums[i], bag[i-1])
        
        print(bag)
        return bag[-1]
        pass

    def rob(self, nums: List[int]) -> int:
        if len(nums) <= 2:
            return max(nums)
        return self.solve(nums)
        pass

一樣是需要巧思才能快速解的動態規劃題目。
這題的重點在於兩個袋子,一個是昨天的一個是前天的,
要選擇前天的+今天搶的,還是今天跳過這家用昨天的袋子呢...


上一篇
Day 20 TensorFlowJS
下一篇
Day 22 bert 文字情感分類
系列文
機器學習與前端網頁30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言