- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 43 lines of Go from the credited upstream file 660F.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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/big"7 "sort"8)9 1011type vec60 struct{ x, y int }12func (a vec60) sub(b vec60) vec60 { return vec60{a.x - b.x, a.y - b.y} }13func (a vec60) dot(b vec60) int { return a.x*b.x + a.y*b.y }14func (a vec60) detCmp(b vec60) int {15 v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))16 w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))17 return v.Cmp(w)18}19 20func cf660F(in io.Reader, out io.Writer) {21 var n, v, s, s2, ans int22 Fscan(in, &n)23 q := []vec60{{}}24 for i := 1; i <= n; i++ {25 Fscan(in, &v)26 s += v27 s2 += v * i28 29 p := vec60{-s, 1}30 j := sort.Search(len(q)-1, func(j int) bool { return p.dot(q[j]) > p.dot(q[j+1]) })31 ans = max(ans, p.dot(q[j])+s2)32 33 p = vec60{i, s*i - s2}34 for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(p.sub(q[len(q)-1])) >= 0 {35 q = q[:len(q)-1]36 }37 q = append(q, p)38 }39 Fprint(out, ans)40}41 4243