Skip to content

915. Partition Array into Disjoint Intervals 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int partitionDisjoint(vector<int>& nums) {
    const int n = nums.size();
    vector<int> mn(n);
    mn[n - 1] = nums[n - 1];
    int mx = INT_MIN;

    for (int i = n - 2; i >= 0; --i)
      mn[i] = min(mn[i + 1], nums[i]);

    for (int i = 0; i < n; ++i) {
      mx = max(mx, nums[i]);
      if (mx <= mn[i + 1])
        return i + 1;
    }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int partitionDisjoint(int[] nums) {
    final int n = nums.length;
    int[] mn = new int[n];
    mn[n - 1] = nums[n - 1];
    int mx = Integer.MIN_VALUE;

    for (int i = n - 2; i >= 0; --i)
      mn[i] = Math.min(mn[i + 1], nums[i]);

    for (int i = 0; i < n; ++i) {
      mx = Math.max(mx, nums[i]);
      if (mx <= mn[i + 1])
        return i + 1;
    }

    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def partitionDisjoint(self, nums: list[int]) -> int:
    n = len(nums)
    mn = [0] * (n - 1) + [nums[-1]]
    mx = -math.inf

    for i in range(n - 2, - 1, -1):
      mn[i] = min(mn[i + 1], nums[i])

    for i, num in enumerate(nums):
      mx = max(mx, num)
      if mx <= mn[i + 1]:
        return i + 1