[Array] C_5372. Gradually sum to get the minimum value of positive number (enumeration / prefix sum)

1. Title Description

Gives you an array of integers nums. You can choose any positive startValue as the initial value.

You need to traverse the nums array from left to right and accumulate the values ​​in the nums array in turn.

Please make sure that the cumulative sum is always greater than or equal to 1 and choose a smallest positive number as startValue.

输入:nums = [-3,2,-3,4,2]
输出:5
解释:如果你选择 startValue = 4,在第三次累加时,和小于 1 。
                累加求和
                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

Method 1: Enumeration

public int minStartValue(int[] nums) {
    int st = Integer.MAX_VALUE;
    int t = -1;

    for (int i = 1; i < Integer.MAX_VALUE; i++) {
        st = i;
        int sum = st;
        boolean flag = true;
        for (int j = 0; j < nums.length; j++) {
            sum += nums[j];
            if (sum < 1) {
                flag = false;
                break;
            }
        }
        if (flag) {
            return st;
        }
    }
    return st;
}

Complexity analysis

  • time complexity: O ( . . . ) O(...) ,
  • Space complexity: O ( 1 ) O (1)

Method 2: Prefix and

  • Think of it this way: because the goal is to make the smallest prefix and value appearing in the accumulation process greater than 1,
  • Therefore, we need to record the min value of the result obtained after each accumulation.
  • Finally, the formula x-min> = 1 gives: x = 1-min
public int minStartValue(int[] nums) {
    int prefix = 0, min = 0;
    for (int n : nums) {
        prefix += n;
        min = Math.min(min, prefix);
    }
    return 1 - min;
}

Complexity analysis

  • time complexity: O ( n ) O (n)
  • Space complexity: O ( 1 ) O (1)

Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105616034