0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

LeetCode日本語修行2日目- [213- House Robber]

Posted at

HouseRobberで適切な日本語は何。。。
強盗?
泥棒?

House Robber

参考:https://leetcode-cn.com/problems/house-robber-ii/

問題の内容

今、プロの泥棒としてのあなた、壮大な目標がありまう。

この町の全ての家を盗む。

各家に一定の現金が隠れています。
家と家並んでて、丸に成っています、最初と最後の家がくっついているということです。
また、家と家の間に防犯システムがあります。隣の家が同じ夜に入られたら、自動的に通報します。
各家の現金を整数配列を指定します。
警報装置に触せず、最高額を目指せよ
通訳、難しい。。。

例:

示例 1:

入力:nums = [2,3,2]
出力:3
解释:一番と三番は繋いでいますので、同じ夜で盗むは禁止。

示例 2:

入力:nums = [1,2,3,1]
出力:4
解释:一番と三番 1+3

示例 3:

输入:nums = [0]
输出:0

ヒント:

1 <= nums.length <= 100
0 <= nums[i] <= 1000


今回は、198の問題ほぼ同じですが、相違点は、最初と最後の家が繋いで
この場合、二つの状況に分けましょう。
一つは最初の家に手を出す、この場合:nums計算範囲は0...nums.size-2
も一つは最初の家に手を出さない、この場合:nums計算範囲は1...nums.size-1
そして、それぞれの条件の結果を出す、二つを比較して、 OK

class Solution {
    fun rob(nums: IntArray): Int {
        if(nums.size == 1){
            return nums[0]
        } else if(nums.size == 2){
            return Math.max(nums[0],nums[1])
        } else{
            return Math.max(myRob(0,nums.size-1,nums),myRob(1,nums.size,nums))
        }

    }

    fun myRob(start: Int,end: Int,nums: IntArray) : Int{
        var pre = nums[start]
        var cur = Math.max(nums[start],nums[start+1])

        for(i in start+2 until end){
            var temp = cur
            cur = Math.max(cur,pre + nums[i])
            pre = temp
        }
        return cur
    }
}








0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?