Problem solution · Go

Codeforces 547B — Mike and Feet

Codeforces 547B — Mike and Feet: a Go solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Sliding window or two pointers
Source
EndlessCheng Codeforces Go
Length
59 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Codeforces 547B — Mike and Feet, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. 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.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 547B — Mike and Feet · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // https://space.bilibili.com/206214func CF547B(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	max := func(a, b int) int {		if b > a {			return b		}		return a	} 	var n int	Fscan(in, &n)	a := make([]int, n)	left := make([]int, n)	st := []int{-1}	for i := range a {		Fscan(in, &a[i])		for len(st) > 1 && a[st[len(st)-1]] >= a[i] {			st = st[:len(st)-1]		}		left[i] = st[len(st)-1]		st = append(st, i)	} 	right := make([]int, n)	st = []int{n}	for i := n - 1; i >= 0; i-- {		for len(st) > 1 && a[st[len(st)-1]] >= a[i] {			st = st[:len(st)-1]		}		right[i] = st[len(st)-1]		st = append(st, i)	} 	ans := make([]int, n+1)	for i, v := range a {		size := right[i] - left[i] - 1		ans[size] = max(ans[size], v)	}	for i := n - 1; i > 0; i-- {		ans[i] = max(ans[i], ans[i+1])	}	for _, v := range ans[1:] {		Fprint(out, v, " ")	}} //func main() { CF547B(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗