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;
}
};