- 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
- 59 lines of Go from the credited upstream file 547B.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 "bufio"5 . "fmt"6 "io"7)8 910func CF547B(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 max := func(a, b int) int {15 if b > a {16 return b17 }18 return a19 }20 21 var n int22 Fscan(in, &n)23 a := make([]int, n)24 left := make([]int, n)25 st := []int{-1}26 for i := range a {27 Fscan(in, &a[i])28 for len(st) > 1 && a[st[len(st)-1]] >= a[i] {29 st = st[:len(st)-1]30 }31 left[i] = st[len(st)-1]32 st = append(st, i)33 }34 35 right := make([]int, n)36 st = []int{n}37 for i := n - 1; i >= 0; i-- {38 for len(st) > 1 && a[st[len(st)-1]] >= a[i] {39 st = st[:len(st)-1]40 }41 right[i] = st[len(st)-1]42 st = append(st, i)43 }44 45 ans := make([]int, n+1)46 for i, v := range a {47 size := right[i] - left[i] - 148 ans[size] = max(ans[size], v)49 }50 for i := n - 1; i > 0; i-- {51 ans[i] = max(ans[i], ans[i+1])52 }53 for _, v := range ans[1:] {54 Fprint(out, v, " ")55 }56}57 5859