All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1901_2000.s1911_maximum_alternating_subsequence_sum.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g1901_2000.s1911_maximum_alternating_subsequence_sum;

// #Medium #Array #Dynamic_Programming #2022_05_14_Time_12_ms_(51.75%)_Space_97.4_MB_(59.03%)

public class Solution {
    public long maxAlternatingSum(int[] nums) {
        int n = nums.length;
        long even = nums[0];
        long odd = 0;
        for (int i = 1; i < n; i++) {
            even = Math.max(even, Math.max(odd + nums[i], nums[i]));
            odd = Math.max(odd, Math.max(even - nums[i], 0));
        }
        return Math.max(even, odd);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy