1911. Maximum Alternating Subsequence Sum(DP)(bb)

First, you would notice this question is quite annoying because odd and even indices would change while you choose different subsequences.

And you would notice that other indices could be even or odd in a subsequence except for the first index.

Here we write down the formula for the index even and odd.

Even = odd + nums[i];

odd = even - nums[i];

and you know that the index for an array is [0.......n]

so even would add the nums first.

Let's say even and odd both start with 0 in index 0.

if you want to figure out why it can work.

you can try to think in this way.

The odd would help to store the previous state, the state you haven't add the number. by this, you can everytime have a two different position's difference, it is actually very brain teasing. However, once you understand the machanics. it is not hard anymore.

every time you would try to take the next number, you would deduct it, and next time you would add a number, if the sum is not larger than the ans, you would reset to the state that havent took the number. you would find a pattern and repeat this untill all the element have been though.

class Solution {
public:
    long long maxAlternatingSum(vector<int>& nums) {
        long long even = 0;
        long long odd = 0;
        for(int i = 0; i < nums.size(); i++){
            even = max(even, odd + nums[i]);
            odd = even - nums[i];
        }
        return even;
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值