- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 78 lines of Go from the credited upstream file 1107G.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6 "math/bits"7 "slices"8)9 1011type st07 [][19][2]int12 13func newST07(a []int) st07 {14 n := len(a)15 st := make(st07, n)16 for i, v := range a {17 st[i][0] = [2]int{v, v}18 }19 for j := 1; j < 19; j++ {20 for i := range n - 1<<j + 1 {21 st[i][j][0] = min(st[i][j-1][0], st[i+1<<(j-1)][j-1][0])22 st[i][j][1] = max(st[i][j-1][1], st[i+1<<(j-1)][j-1][1])23 }24 }25 return st26}27 28func (st st07) query(l, r int) [2]int {29 k := bits.Len(uint(r-l)) - 130 p, q := st[l][k], st[r-1<<k][k]31 return [2]int{min(p[0], q[0]), max(p[1], q[1])}32}33 34func cf1107G(in io.Reader, out io.Writer) {35 var n, earn, c, ans int36 Fscan(in, &n, &earn)37 d := make([]int, n)38 s := make([]int, n+1)39 for i := range d {40 Fscan(in, &d[i], &c)41 s[i+1] = s[i] + earn - c42 ans = max(ans, earn-c)43 }44 t := newST07(s)45 46 type pair struct{ d, i int }47 ds := make([]pair, n-1)48 left := make([]int, n-1)49 st := []int{-1}50 for i := range n - 1 {51 v := d[i+1] - d[i]52 ds[i] = pair{v, i}53 for len(st) > 1 && d[st[len(st)-1]+1]-d[st[len(st)-1]] <= v {54 st = st[:len(st)-1]55 }56 left[i] = st[len(st)-1]57 st = append(st, i)58 }59 right := make([]int, n-1)60 st = []int{n - 1}61 for i := n - 2; i >= 0; i-- {62 for len(st) > 1 && d[st[len(st)-1]+1]-d[st[len(st)-1]] <= d[i+1]-d[i] {63 st = st[:len(st)-1]64 }65 right[i] = st[len(st)-1]66 st = append(st, i)67 }68 69 slices.SortFunc(ds, func(a, b pair) int { return a.d - b.d })70 for _, p := range ds {71 i := p.i72 ans = max(ans, t.query(i+2, right[i]+2)[1]-t.query(left[i]+1, i+1)[0]-p.d*p.d)73 }74 Fprint(out, ans)75}76 7778