[LeetCode] Minimum Value to Get Positive Step by Step Sum

준규·2023년 3월 23일
0

1.문제


Given an array of integers nums, you start with an initial positive value startValue.

In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

Return the minimum positive value of startValue such that the step by step sum is never less than 1.


정수 배열 nums가 주어질 때 양수의 initial 수에 왼쪽으로부터 오른쪽 까지 하나씩 더한다.

더했을때 합이 1보다 작지 않은 initial 수 중 가장 작은 값을 리턴하는 문제이다.


Example 1

Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
  (4 -3 ) = 1  | (5 -3 ) = 2    |  -3
  (1 +2 ) = 3  | (2 +2 ) = 4    |   2
  (3 -3 ) = 0  | (4 -3 ) = 1    |  -3
  (0 +4 ) = 4  | (1 +4 ) = 5    |   4
  (4 +2 ) = 6  | (5 +2 ) = 7    |   2

Example 2

Input: nums = [1,2]
Output: 1
Explanation: Minimum start value should be positive. 

Example 3

Input: nums = [1,-2,-3]
Output: 5

Constraints:

  • 1 <= nums.length <= 100
  • -100 <= nums[i] <= 100

2.풀이

  1. nums을 순회하면서 각 요소와 현재 수의 합을 구한다.
  2. 현재의 합이 1보다 작은지 체크한다. 만약 작다면 for문을 중지시킨다.

/**
 * @param {number[]} nums
 * @return {number}
 */
const minStartValue = function (nums) {
  for (let i = 1; i > 0; i++) {
    let currentSum = i;
    // nums배열을 순회한다
    for (let j = 0; j < nums.length; j++) {
      // 현재까지의 합을 저장
      currentSum = currentSum + nums[j];
      // 만약 현재 합이 1보다 작으면 break
      if (currentSum < 1) {
        break;
      }
    }

    // 만약 현재 합이 1이상이라면 그대로 i를 리턴해준다.
    if (currentSum < 1) {
      continue;
    } else {
      return i;
    }
  }
};

3.결과

profile
안녕하세요 :)

0개의 댓글