GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #2036 - Maximum Alternating Subarray Sum - LeetCode JavaScript Solutions

Back to all solutions

#2036 - Maximum Alternating Subarray Sum

Medium • View on LeetCode • View on GitHub
Array Dynamic Programming

Problem Description

A subarray of a 0-indexed integer array is a contiguous non-empty sequence of elements within an array.

The alternating subarray sum of a subarray that ranges from index i to j (inclusive, 0 <= i <= j < nums.length) is nums[i] - nums[i+1] + nums[i+2] - ... +/- nums[j].

Given a 0-indexed integer array nums, return the maximum alternating subarray sum of any subarray of nums.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var maximumAlternatingSubarraySum = function(nums) {
  let result = -Infinity;
  let positive = -Infinity;
  let negative = -Infinity;

  for (const num of nums) {
    const newPositive = Math.max(negative + num, num);
    const newNegative = positive - num;

    positive = newPositive;
    negative = newNegative;
    result = Math.max(result, positive, negative);
  }

  return result;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.