2276. Count Integers in Intervals
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class CountIntervals {
    TreeMap<Integer, Integer> intervals;
    int total;

    public CountIntervals() {
        intervals = new TreeMap<>();
        total = 0;
    }

    public void add(int left, int right) {
        if (intervals.floorKey(right) == null || intervals.get(intervals.floorKey(right)) < left) {
            intervals.put(left, right);
            total += (right - left + 1);
        } else {
            int newLeft = left;
            int newRight = right;

            while (true) {
                int floorKey = intervals.floorKey(newRight);
                int end = intervals.get(floorKey);
                newLeft = Math.min(newLeft, floorKey);
                newRight = Math.max(newRight, end);
                total -= (end - floorKey + 1);
                intervals.remove(floorKey);

                if (intervals.floorKey(newRight) == null || intervals.get(intervals.floorKey(newRight)) < newLeft) {
                    break;
                }
            }

            intervals.put(newLeft, newRight);
            total += (newRight - newLeft + 1);
        }
    }

    public int count() {
        return total;
    }
}

```
['Java']