leetcode-740. 删除并获得点数

题目

740. 删除并获得点数

解法

class Solution {
    
    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function deleteAndEarn($nums) {
        $sum = [];
        
        $max = 0;
        foreach ($nums as $num) {
            $sum[$num] += $num;
            $max = max($num, $max);
        }
        
        return $this->rob($sum, $max);
    }
    
    function rob($nums, $size) {
        $first  = $nums[0];
        $second = max($nums[1], $nums[0]);
        
        for ($i = 2; $i <= $size; $i++) {
            $tmp    = $second;
            $second = max($first + $nums[$i], $second);
            $first  = $tmp;
        }
        
        return $second;
    }
}

参考

https://leetcode-cn.com/problems/delete-and-earn/solution/shan-chu-bing-huo-de-dian-shu-by-leetcod-x1pu/

posted @ 2022-01-08 17:04  吴丹阳-V  阅读(32)  评论(0编辑  收藏  举报