Skip to content

3096. Minimum Levels to Gain More Points

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int minimumLevels(vector<int>& possible) {
    const int n = possible.size();
    const vector<int> nums = getNums(possible);
    vector<int> prefix(n + 1);

    partial_sum(nums.begin(), nums.end(), prefix.begin() + 1);

    for (int i = 1; i < n; ++i)
      if (prefix[i] > prefix[n] - prefix[i])
        return i;

    return -1;
  }

 private:
  vector<int> getNums(const vector<int>& possible) {
    vector<int> nums;
    for (const int num : possible)
      nums.push_back(num == 1 ? 1 : -1);
    return nums;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int minimumLevels(int[] possible) {
    final int n = possible.length;
    final int[] nums = getNums(possible);
    int[] prefix = new int[n + 1];

    for (int i = 0; i < n; ++i)
      prefix[i + 1] = prefix[i] + nums[i];

    for (int i = 1; i < n; ++i)
      if (prefix[i] > prefix[n] - prefix[i])
        return i;

    return -1;
  }

  private int[] getNums(int[] possible) {
    int[] nums = new int[possible.length];
    for (int i = 0; i < possible.length; ++i)
      nums[i] = possible[i] == 0 ? -1 : 1;
    return nums;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minimumLevels(self, possible: list[int]) -> int:
    n = len(possible)
    nums = [num if num == 1 else -1 for num in possible]
    prefix = list(itertools.accumulate(nums, initial=0))

    for i in range(1, n):
      if prefix[i] > prefix[n] - prefix[i]:
        return i

    return -1