- 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
- 76 lines of Go from the credited upstream file 1494C.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 "sort"8)9 1011func CF1494C(_r io.Reader, _w io.Writer) {12 in := bufio.NewReader(_r)13 out := bufio.NewWriter(_w)14 defer out.Flush()15 max := func(a, b int) int {16 if b > a {17 return b18 }19 return a20 }21 22 var T, n, m int23 for Fscan(in, &T); T > 0; T-- {24 Fscan(in, &n, &m)25 a := make([]int, n)26 for i := range a {27 Fscan(in, &a[i])28 }29 b := make([]int, m)30 for i := range b {31 Fscan(in, &b[i])32 }33 f := func(a, b []int) int {34 same, i, n := 0, 0, len(a)35 for _, v := range b {36 for i < n && a[i] < v {37 i++38 }39 if i < n && a[i] == v {40 same++41 i++42 }43 }44 res := same45 i, left := 0, 046 for right, v := range b {47 for i < n && a[i] < v {48 i++49 }50 if i < n && a[i] == v {51 same--52 i++53 }54 for left <= right && v-b[left]+1 > i { 55 left++56 }57 res = max(res, right-left+1+same)58 }59 return res60 }61 x, y := sort.SearchInts(a, 0), sort.SearchInts(b, 0)62 ans := f(a[x:], b[y:])63 64 for i := 0; i < (x+1)/2; i++ {65 a[i], a[x-1-i] = -a[x-1-i], -a[i]66 }67 for i := 0; i < (y+1)/2; i++ {68 b[i], b[y-1-i] = -b[y-1-i], -b[i]69 }70 ans += f(a[:x], b[:y])71 Fprintln(out, ans)72 }73}74 7576