Leetcode 3196. Maximize Total Cost of Alternating Subarrays

  • [Leetcode 3196. Maximize Total Cost of Alternating Subarrays](#Leetcode 3196. Maximize Total Cost of Alternating Subarrays)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题就是一个动态规划,只需要考虑每一个元素作为开始和处于序列当中的二元态即可,其中,如果处在序列当中但刚好在奇数的位置,那么两种情况刚好可以归并。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def maximumTotalCost(self, nums: List[int]) -> int:
        n = len(nums)
        
        @lru_cache(None)
        def dp(idx, stat):
            if idx >= n:
                return 0
            if stat == 0:
                return nums[idx] + dp(idx+1, 1)
            else:
                return max(nums[idx] + dp(idx+1, 1), -nums[idx] + dp(idx+1, 0))
            
        return dp(0, 0)

提交代码评测得到:耗时881ms,占用内存287.9MB。

相关推荐
海绵宝宝转agent3 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi5 小时前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
UIU11416 小时前
P1233 [ICPC 2001 Taejon R] 木棍加工
数据结构·c++·算法·动态规划
j7~21 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing1 天前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing1 天前
LeetCode100 11. 盛最多水的容器
算法·leetcode
海绵宝宝转agent1 天前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先
Rain的Java大神之路1 天前
面试被LeetCode 27(移除元素)问懵?别再用两层 for 循环了:一道“简单题”吃透双指针原地删除,附面试加分话术 + 11 个避坑清单
后端·leetcode·面试
重生之小比特1 天前
【算法拾光】前缀和|连续的子数组和 + 和相同的二元子数组
算法·leetcode·哈希算法