- 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
- 96 lines of Go from the credited upstream file 1313C2.go.
- The implementation visibly relies on sequence storage.
- 2 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 "bufio"5 . "fmt"6 "io"7)8 910func CF1313C2(_r io.Reader, _w io.Writer) {11 in := bufio.NewReader(_r)12 out := bufio.NewWriter(_w)13 defer out.Flush()14 min := func(a, b int) int {15 if a < b {16 return a17 }18 return b19 }20 21 var n int22 Fscan(in, &n)23 a := make([]int, n)24 for i := range a {25 Fscan(in, &a[i])26 }27 28 type pair struct{ v, i int }29 posL := make([]int, n)30 stack := []pair{{0, -1}}31 for i, v := range a {32 for {33 if top := stack[len(stack)-1]; top.v <= v {34 posL[i] = top.i35 break36 }37 stack = stack[:len(stack)-1]38 }39 stack = append(stack, pair{v, i})40 }41 posR := make([]int, n)42 stack = []pair{{0, n}}43 for i := n - 1; i >= 0; i-- {44 v := a[i]45 for {46 if top := stack[len(stack)-1]; top.v <= v {47 posR[i] = top.i48 break49 }50 stack = stack[:len(stack)-1]51 }52 stack = append(stack, pair{v, i})53 }54 55 dpl := make([]int64, n)56 dpl[0] = int64(a[0])57 for i := 1; i < n; i++ {58 l := posL[i]59 dpl[i] = int64(a[i]) * int64(i-l)60 if l >= 0 {61 dpl[i] += dpl[l]62 }63 }64 dpr := make([]int64, n)65 dpr[n-1] = int64(a[n-1])66 for i := n - 2; i >= 0; i-- {67 r := posR[i]68 dpr[i] = int64(a[i]) * int64(r-i)69 if r < n {70 dpr[i] += dpr[r]71 }72 }73 74 maxAns, maxPos := int64(0), 075 for i, v := range a {76 if ans := dpl[i] + dpr[i] - int64(v); ans > maxAns {77 maxAns, maxPos = ans, i78 }79 }80 81 ans := make([]interface{}, n)82 curMax := a[maxPos]83 for j := maxPos; j >= 0; j-- {84 curMax = min(curMax, a[j])85 ans[j] = curMax86 }87 curMax = a[maxPos]88 for j := maxPos + 1; j < n; j++ {89 curMax = min(curMax, a[j])90 ans[j] = curMax91 }92 Fprint(out, ans...)93}94 9596