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 — #3511 - Make a Positive Array - LeetCode JavaScript Solutions

Back to all solutions

#3511 - Make a Positive Array

Medium • View on LeetCode • View on GitHub
Array Greedy Prefix Sum

Problem Description

You are given an array nums. An array is considered positive if the sum of all numbers in each subarray with more than two elements is positive.

You can perform the following operation any number of times:

  • Replace one element in nums with any integer between -1018 and 1018.

Find the minimum number of operations needed to make nums positive.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var makeArrayPositive = function(nums) {
  let result = 0;
  let lowestSum = nums[0] + nums[1];

  for (let i = 2; i < nums.length; i++) {
    const currentValue = nums[i];
    const currentTriplet = currentValue + nums[i - 1] + nums[i - 2];
    lowestSum = Math.min(lowestSum + currentValue, currentTriplet);

    if (lowestSum <= 0) {
      nums[i] = lowestSum = 10 ** 18;
      result++;
    }
  }

  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.