← Home
```go
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)

	var n int
	if _, err := fmt.Fscan(in, &n); err != nil {
		return
	}

	totalTime := 0
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(in, &a)
		totalTime += a
	}

	var m int
	fmt.Fscan(in, &m)

	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscan(in, &l, &r)

		// We need to submit all problems. The earliest we can have all solutions is totalTime.
		// We can submit them at time t if t >= totalTime and l <= t <= r.
		// Since we want the minimal time, we look for the first interval where r >= totalTime.
		// If r < totalTime, this interval ends before we finish solving, so we can't use it to submit the last problem.
		if r >= totalTime {
			if l >= totalTime {
				// We finished solving before this interval started.
				// We have to wait until the start of this interval.
				fmt.Println(l)
			} else {
				// We finished solving inside this interval (since l < totalTime <= r).
				// We can submit immediately upon finishing.
				fmt.Println(totalTime)
			}
			return
		}
	}

	// If no suitable interval is found
	fmt.Println("-1")
}
```