jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>

#define P 1000000007

int comp(const void *a, const void *b){return *(int*)a-*(int*)b;}
int compw(const void *a, const void *b){return (*(int*)a>*(int*)b)-(*(int*)a<*(int*)b);}
int compr(const void *a, const void *b){return *(int*)b-*(int*)a;}

uint32_t nextpint(void){ char c=getchar(); while(c<'0'||'9'<c) c=getchar(); uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }

inline int max2(const int a, const int b){return a>b?a:b;}
inline int min2(const int a, const int b){return a>b?b:a;}
inline int dif2(const int a, const int b){return a>b?a-b:b-a;}

int a[200000];
int main(void){
	int k=nextpint();
	int n=nextpint();
	for(int i=0; i<n; i++){
		a[i]=nextpint();
	}
	int ans=k+a[0]-a[n-1];
	for(int i=0; i<n-1; i++){
		int now=a[i+1]-a[i];
		if(now>ans) ans=now;
	}
	printf("%d\n", k-ans);
}
//  [c]
#include <stdio.h>

int main(void){
  int n,k,max=0;
  int a[100005];
  
  scanf("%d %d", &k, &n);
  //scanf("%lld", &k);
      
  for(int i =0;i<n;i++){
    scanf("%d", &a[i]);
  }
  
  max = k-a[n-1]+a[0];
  
  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }
  
  printf("%d", k-max);
  return 0;
}
//  [c]
#include <stdio.h>

int main(void){
  long int n,k,max=0;
  long int a[100005];
  
  scanf("%ld %ld", &k, &n);
  //scanf("%lld", &k);
      
  for(int i =0;i<n;i++){
    scanf("%ld", &a[i]);
  }
  
  max = k-a[n-1]+a[0];
  
  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }
  
  printf("%d", k-max);
  return 0;
}
//  [c]
#include <stdio.h>

int main(void){
  long long int n,k,max=0;
  long long int a[100005];
  
  scanf("%lld %lld", &k, &n);
  //scanf("%lld", &k);
      
  for(int i =0;i<n;i++){
    scanf("%lld", &a[i]);
  }
  
  max = k-a[n-1]+a[0];
  
  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }
  
  printf("%d", k-max);
  return 0;
}
//  [javascript]
  // inputに入力データ全体が入る
  function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");
  var K = Number(tmp[0]);
  var N = Number(tmp[1]);
	//文字列から10進数に変換するときはparseIntを使います
  tmp = input[1].split(" ");
  for(i=0; i<tmp.length; i++){
    tmp[i] = Number(tmp[i]);
  }


  var max = 0;
  for (var i = 1; i < tmp.length; i++) {
    dis = tmp[i] - tmp[i-1];
    if(dis > max) max = dis;
  }
  dis = K - (tmp[tmp.length-1] - tmp[0]);
  if(dis > max) max = dis;
	//出力
	console.log('%d', K-max);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    var S = input.split('\n');
    var K = S[0].split(' ')[0];
    var N = S[0].split(' ')[1];
    var A = S[1].split(' ');
    var count = 0;
    for (var i = 0; i < N; i++) {
        var sa = A[i] - A[i + 1];
        if (Math.abs(sa) > count) {
            count = Math.abs(sa);
        }
    }
    if (K - (A[N - 1] - A[0]) > count) {
        count = K - (A[N - 1] - A[0]);        
    }
    console.log(K - count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const K = Number(arg[0].split(" ")[0]);
    const N = Number(arg[0].split(" ")[1]);
    const A = arg[1].split(" ").map(Number);
    
    let longestDistances = 0;
    
    // 区間を作る
    for(let i=0; i<N; i++) {
        let distance;
        
        if(Number(i) === N - 1) {
            distance = (K - A[i]) + A[0];
        } else {
            distance = A[Number(i) + 1] - A[i];
        }
        
        if(longestDistances < distance) {
            longestDistances = distance;
        }
    }
    
    const answer = K - longestDistances;
    
    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
const input = require("fs").readFileSync("/dev/stdin", "utf8")

;(input => {

    const lines = input.split('\n')
    const [K, N] = lines[0].split(' ').map(Number)
    const A = lines[1].split(' ').map(Number)

    const diff = []
    diff[0] = A[0] + K - A[N - 1]
    for (let i = 1; i < N; i++) {
        diff[i] = A[i] - A[i - 1]
    }
    console.log(K - Math.max(...diff))

})(input)
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

var lines = []
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', (line) => {
  lines.push(line);
});

reader.on('close', () => {
 var kn = lines[0].split(' ');
 var k = Number(kn[0]);
 var n = Number(kn[1]);
 var a = lines[1].split(' ');
 a = a.map(function(str) { return Number(str)});
 // console.log(a);
 var kyori = [];
 kyori.push(k+a[0] - a[n-1]);

 for(i=0; i<n-1; i++){
   kyori.push(a[i+1] - a[i]);
 }

 // console.log(kyori);
 var max = Math.max(...kyori);
 var index = kyori.indexOf(max);
 kyori.splice(index,1);
 // console.log(kyori);
 var ans = kyori.reduce(function(a, x){return a + x;});
 console.log(ans);
});
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

var lines = []
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', (line) => {
  lines.push(line);
});

reader.on('close', () => {
 var kn = lines[0].split(' ');
 var k = Number(kn[0]);
 var n = Number(kn[1]);
 var a = lines[1].split(' ');
 // console.log(a);
 var kyori = [];
 kyori.push(k+a[0] - a[n-1]);

 for(i=0; i<n-1; i++){
   kyori.push(a[i+1] - a[i]);
 }

 // console.log(kyori);
 var max = Math.max(...kyori);
 var index = kyori.indexOf(max);
 kyori.splice(index,1);
 // console.log(kyori);
 var ans = kyori.reduce(function(a, x){return a + x;});
 console.log(ans);
});
//  [go]
package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

type BufferedWriter interface {
    Printf(format string, a ...interface{})
    Flush()
}

type writerImpl struct {
    *bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
    return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
    fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
    impl.Writer.Flush()
}

type WordScanner interface {
    NextInt() int
    NextInt64() int64
    NextString() string
}

type wordScannerImpl struct {
    *bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
    s := bufio.NewScanner(reader)
    s.Split(bufio.ScanWords)
    return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
    impl.Scan()
    bb := impl.Bytes()
    i := 0
    for _, b := range bb {
        i *= 10
        i += int(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
    impl.Scan()
    bb := impl.Bytes()
    i := int64(0)
    for _, b := range bb {
        i *= 10
        i += int64(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextString() string {
    impl.Scan()
    return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
    defer writer.Flush()
    k, n := reader.NextInt64(), reader.NextInt64()
    aa := make([]int64, n)
    for i := int64(0); i < n; i++ {
        aa[i] = reader.NextInt64()
    }
    diffToPrev := make([]int64, n)
    diffToPrev[0] = aa[0] + k - aa[len(aa)-1]
    for i := int64(1); i < n; i++ {
        diffToPrev[i] = aa[i] - aa[i-1]
    }
    maxSoFar := diffToPrev[0]
    for i := int64(1); i < n; i++ {
        if diffToPrev[i] > maxSoFar {
            maxSoFar = diffToPrev[i]
        }
    }
    writer.Printf("%d\n", k - maxSoFar)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
	"strings"

)


func main() {
	solve(os.Stdin, os.Stdout)
}

type ReaderEx struct {
	baseScanner *bufio.Scanner
	words       []string
	nextWordIdx func() int
	initWordIdx func(int)
}

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	var wordsCnt int
	this.baseScanner = bufio.NewScanner(stdin)
	this.baseScanner.Buffer(make([]byte, 0), 1E+11)
	this.nextWordIdx = func() int {
		cur := idx
		idx = (idx + 1) % wordsCnt
		return cur
	}
	this.initWordIdx = func(wc int) {
		idx = 0
		wordsCnt = wc
	}
	return &this
}

func (me *ReaderEx) Scan(doSplit bool) (isScanned bool) {
	isScanned = me.baseScanner.Scan()
	if doSplit {
		me.words = strings.Fields(me.baseScanner.Text())
	} else {
		me.words = []string{me.baseScanner.Text()}
	}
	me.initWordIdx(len(me.words))
	return
}

func (me *ReaderEx) nextBytes() []byte {
	return []byte(me.words[me.nextWordIdx()])
}
func (me *ReaderEx) nextString() string {
	return me.words[me.nextWordIdx()]
}

type StringArray []string

func (me *ReaderEx) nextStringArray() StringArray {
	return me.words[me.nextWordIdx():]
}

func (me StringArray) toStrings() []string {
	return me
}

func (me StringArray) toInts() []int {
	strValues := me.toStrings()
	values := make([]int, len(strValues))
	for i, v := range strValues {
		n, err := strconv.Atoi(v)
		if err != nil {
			panic(err)
		}
		values[i] = n
	}
	return values
}
func (me *ReaderEx) nextInt() int {
	n, err := strconv.Atoi(me.words[me.nextWordIdx()])

	defer func() {
		if err != nil {
			panic(fmt.Sprintf("getInt(%d)", n))
		}
	}()
	return n
}

func pow(x, y, mod int) (ans int) {

	ans = 1
	for bit := 1 << uint(math.Floor(math.Log2(float64(y)))); ; bit >>= 1 {
		if y&bit != 0 {
			ans *= x
			if mod > 0 {
				ans %= mod
			}
		}
		if bit <= 1 {
			return
		}
		ans *= ans
		if mod > 0 {
			ans %= mod
		}
	}
}

type factType struct {
	prime int
	count int
}

func fact(n int) (facts []*factType) {

	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			fa := factType{prime: i}
			for n%fa.prime == 0 {
				n /= fa.prime
				fa.count++
			}
			facts = append(facts, &fa)
		}
	}
	if n > 1 {
		facts = append(facts, &factType{prime: n, count: 1})
	}
	return facts
}
func dec2bin(n int) (ret []bool) {
	for bit := 1 << uint(math.Floor(math.Log2(float64(n)))); ; bit >>= 1 {
		ret = append(ret, n&bit != 0)

		if bit <= 1 {
			return
		}
	}

}

func abs(v int) int {
	if v < 0 {
		v = -v
	}
	return v
}

func b2i(b bool) (i int) {
	if b {
		i = 1
	} else {
		i = 0
	}
	return
}

func solve(stdin io.Reader, stdout io.Writer) {

	r := NewScannerEx(stdin)
	r.Scan(true)
	k, n := r.nextInt(), r.nextInt()
	r.Scan(true)
	a := r.nextStringArray().toInts()

	m := k - a[n-1] + a[0]
	for i := 1; i < n; i++ {
		w := a[i] - a[i-1]
		if m < w {
			m = w
		}
	}
	fmt.Fprintln(stdout, k-m)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	k := getNextInt(scanner)
	n := getNextInt(scanner)
	aa := make([]int, n+1)
	for i := 0; i < n; i++ {
		aa[i] = getNextInt(scanner)
	}
	aa[n] = k + aa[0]
	var ans int
	ans = k
	for i := 0; i < n; i++ {
		if ans > k-(aa[i+1]-aa[i]) {
			ans = k - (aa[i+1] - aa[i])
		}
	}
	fmt.Fprintln(writer, ans)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	sc := newScanner()
	var k = sc.readInt()
	var n = sc.readInt()
	var a = make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.readInt()
	}
	// proc dist
	var dist = make([]int, n)
	for i := 0; i < n; i++ {
		if i != n-1 {
			dist[i] = a[i+1] - a[i]
		} else {
			dist[i] = a[0] + k - a[i]
		}
	}
	var max int = dist[0]
	for i := 0; i < len(dist); i++ {
		if max < dist[i] {
			max = dist[i]
		}
	}
	fmt.Println(max)

}

//////////////////
//////////////////
//////////////////

func abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func pow(base, exponent int) int {
	if exponent < 0 {
		panic(fmt.Sprintf("exponent (%d) should not be a minus", exponent))
	}

	answer := 1
	for i := 0; i < exponent; i++ {
		answer *= base
	}
	return answer
}

func ceil(divident, dividor int) int {
	if dividor == 0 {
		panic("dividor should not be 0")
	}

	quo := divident / dividor
	rem := divident % dividor

	if rem != 0 {
		if (divident > 0 && dividor > 0) ||
			(divident < 0 && dividor < 0) {
			return quo + 1
		}
	}
	return quo
}

// -   sortutil

func reverseInts(a []int) {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
}

func reverseStrings(a []string) {
	sort.Sort(sort.Reverse(sort.StringSlice(a)))
}

// -   io

type scanner struct {
	bufScanner *bufio.Scanner
}

func newScanner() *scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &scanner{bufSc}
}

func (sc *scanner) readString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *scanner) readInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}

func (sc *scanner) readInt64() int64 {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.ParseInt(text, 10, 64)
	if err != nil {
		panic(err)
	}
	return num
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	k := nextInt()
	n := nextInt()
	alist := make([]int, n)
	kukanlist := make([]int, n)
	maxkukan := -1
	roadmax := 0

	for i := 0; i < n; i++ {
		alist[i] = nextInt()
	}
	for i := 1; i < n; i++ {
		kukanlist[i] = alist[i] - alist[i-1]
		roadmax += kukanlist[i]
	}
	kukanlist[0] = k - alist[n-1]
	roadmax += kukanlist[0]

	for i := 0; i < n; i++ {
		if kukanlist[i] > maxkukan {
			maxkukan = kukanlist[i]
		}
	}

	//fmt.Println(kukanlist, roadmax, maxkukan)
	fmt.Println(roadmax - maxkukan)
}

// ---- readfunc
func scanInit() {
	const cap = 64 * 1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main
 
import (
	"fmt"
)

var K, N, ans, a int
func main() {
	fmt.Scan(&K)
	fmt.Scan(&N)
	for i := 0; i < N; i++ {
		fmt.Scan(&a)
		ans += a % (K / 2)
	}
	fmt.Println(ans)
}
//  [ruby]
k, n = STDIN.gets.split.map(&:to_i)
a_list = STDIN.gets.split.map(&:to_i)

first_a = a_list.shift
max = 0
before_a = first_a

a_list.each do |a|
  s = a - before_a
  before_a = a
  max = s if s > max
end

last_s = k - a_list[-1] + first_a
max = last_s if last_s > max
puts k - max
//  [ruby]
k, n = gets.chomp.split(' ').map{|i| i.to_i }

a1 = 0
old = -1
sum = 0
max = 0

alast = gets.chomp.split(' ').map{|i|
  ii = i.to_i
  if old == -1
    a1 = ii
    old = ii
    next
  end
  diff = ii - old
  sum += diff
  max = diff if max < diff
  old = ii
  ii
}.last

uediff = k - (alast - a1)
sum += uediff
max = uediff if max < uediff

puts sum - max
//  [ruby]
k, n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
1.upto(n - 1) do |i|
    d = a[i] - a[i - 1]
    max = d if d > max
end
d0 = k + a[0] - a[n - 1]
max = d0 if d0 > max
puts k - max
//  [ruby]
k,n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
memo = nil
a.each_cons(2).with_index do |ij,idx|
  i,j = ij
  if j-i > max
    max = j-i
    memo = idx
  end
end
memo = -1 if k - a[-1] + a[0] > max
puts k - (a[memo+1] - a[memo]).abs
//  [ruby]
k,n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
memo = nil
a.each_cons(2).with_index do |ij,idx|
  i,j = ij
  if j-i > max
    max = j-i
    memo = idx
  end
end
if k - a[-1] + a[0] > max
  max = k - a[-1] + a[0]
  memo = -1
end
puts (a[memo+1] - a[memo]).abs
//  [ruby]
K, N = gets.split.map &:to_i
a = gets.split.map &:to_i

a << K - a.max + a.min
a.sort!
puts K - (0..N).map { |i| a[i] - a[i-1] }.max
//  [rust]
use std::io;
use std::cmp;
fn main() {
    let mut s = String::new();
    let mut s2 = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let mut s_spl:Vec<&str> = s.trim().split(' ').collect();
    let k: i32 = s_spl[0].to_string().parse().unwrap();
    let mut max = -1;
    let mut a_first = -1;
    let mut a_old = -1;
    io::stdin().read_line(&mut s2).unwrap();
    for s_loop in s2.trim().split(' ') {
        let a:i32 = s_loop.parse().unwrap();
        if a_old == -1 {
            a_first = a;
        }else {
                max = cmp::max(max, a-a_old);
        }
        a_old = a;
    }
    max = cmp::max(max, k + a_first - a_old);
    println!("{}", k-max);
}
//  [rust]
use proconio::{fastout, input, marker::*};

#[fastout]
fn main() {
    input! {
        k: isize,
        n: usize,
        a: [isize; n],
    }
    let mut ans = 1_000_000_000;
    let mut dp = vec![vec![0; n]; n];

    for i in 0..n {
        let mut dist = 0;
        let mut j = i;
        for x in i+1..n+i {
            let z = if n <= x { x - n } else { x };
            if dp[j][z] == 0 {
                let az = if n == x { k } else { a[z] };
                dp[j][z] = isize::abs(a[j] - az);
            }
            dist += dp[j][z];
            j = z;
        }
        ans = std::cmp::min(ans, dist);
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{fastout, input, marker::*};

#[fastout]
fn main() {
    input! {
        k: isize,
        n: usize,
        a: [isize; n],
    }
    let mut ans = 1_000_000_000;

    for i in 0..n {
        let mut dist = 0;
        let mut j = i;
        for x in i+1..n+i {
            let z = if n <= x { x - n } else { x };
            let az = if n == x { k } else { a[z] };
            dist += isize::abs(a[j] - az);
            j = z;
        }
        ans = std::cmp::min(ans, dist);
    }

    println!("{}", ans);
}
//  [rust]
use proconio::{input, fastout};

#[fastout]
fn main() {
    input! {
        k: usize, n: usize,
        arr: [usize; n],
    }

    let mut a = arr.clone();
    a.sort();
    let dist = a[n-1] - a[0];
    if n == 2 {
        println!("{}", std::cmp::min(dist, k-dist))
    } else {
        println!("{}", dist)
    }
}
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let kn = readInts()
    let (k, n) = (kn[0],kn[1])
    let aryN = readInts()
    var ans = aryN[0] - aryN[n - 1] + k
    for i in 0..<n - 1 {
        ans = max(ans, aryN[i + 1] - aryN[i])
    }
    
    print(k - ans)
}

main()
//  [swift]
import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let array = readLine()!.componentsSeparatedByString(" ").map{ Int($0)! }
var N = 0
var maxDis = 0
for e in array{
  let dist = e - N
  if(dist > maxDis){
    maxDis = dist
  }
  N = e
}
let around = Int(input[0])!
if(around - N + array[0] > maxDis){
  maxDis = around - N + array[0]
}
print(around - maxDis)
//  [swift]
import Foundation

let kn = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
let k = kn[0]
let n = kn[1]

var inputA = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
var minus:[Int] = inputA.map({
    if $0 > 10 {
        return $0 - 20
    } else {
        return $0
    }
})
let plusAns = inputA.maxElement()!-inputA.minElement()!
let minusAns = minus.maxElement()!-minus.minElement()!
print(min(plusAns, minusAns))
//  [swift]
import Foundation

let kn = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
let k = kn[0]
let n = kn[1]

var inputA = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
inputA = inputA.map({
    if $0 > 10 {
        return $0 - 20
    } else {
        return $0
    }
})
inputA = inputA.sort{ $0 < $1 }  
print(inputA.last! - inputA.first!)
//  [swift]
import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let array = readLine()!.componentsSeparatedByString(" ").map{ Int($0)! }
var N = 0
var maxDis = 0
for e in array{
  let dist = e - N
  if(dist > maxDis){
    maxDis = dist
  }
  N = e
}
let around = Int(input[0])!
if(around - N + array[0] > maxDis){
  maxDis = around - N + array[0]
}
print(maxDis)
//  [typescript]
import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var k: number = 0;
    var n: number = 0;
    var an: number[] = [];
    var ans: number = 0;
    // init
    [k, n] = input.shift().split(" ").map(x => Number(x));
    an = input.shift().split(" ").map(x => Number(x));
    // solve
    var max = 0;
    for (var nx = 0; nx < n; nx++) {
        if (nx < n - 1) {
            max = Math.max(max, an[nx + 1] - an[nx]);
        } else {
            max = Math.max(max, k + an[0] - an[nx]);
        }
    }
    ans = k - max;
    // answer
    console.log(ans);
}

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [k, n]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const a: number[] = tmp.shift().split(" ").map(int => int - 0);
    let m = 0;
    for (let i = 0; i < n; i++) {
      if (i < n - 1 && a[i + 1] - a[i] > m) {
        m = a[i + 1] - a[i];
      } else if (i == n - 1 && a[0] + (k - a[i]) > m) {
        m = a[0] + (k - a[i]);
      }
    }
    return `${k - m}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', chunk => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const lake = Number(inputs[0].split(' ')[0]);
  const distance = inputs[1].split(' ').map(Number);
  let max = 0;
  let sum = 0;

  for (let i = 1; i < distance.length; i++) {
    sum += distance[i] - distance[i - 1];

    if (max < distance[i] - distance[i - 1]) {
      max = distance[i] - distance[i - 1];
    }
  }

  if (sum > lake / 2) {
    sum = sum - max + (lake - distance[distance.length - 1]) + distance[0];
  }

  console.log(sum);
}
//  [typescript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', chunk => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const lake = Number(inputs[0].split(' ')[0]);
  const distance = inputs[1].split(' ').map(Number);
  let max = distance[distance.length - 1] - distance[distance.length - 2];
  let sum = 0;

  for (let i = 1; i < distance.length; i++) {
    sum += distance[i] - distance[i - 1];
  }

  if (sum > lake / 2) {
    sum = sum - max + (lake - distance[distance.length - 1]) + distance[0];
  }

  console.log(sum);
}
//  [python]
n = int(input())
s = input()

ans = 0
x = 0
for _ in s:
    if _ == 'I':
        x += 1
    else:
        x -= 1
    ans = max(ans, x)

print(ans)
//  [python]
n = int(input())
s = list(input())
x = 0
xmax = 0
for ss in s:
    if ss == "I":
        x += 1
    else:
        x -= 1
    xmax = max(xmax, x)
print(xmax)
//  [python]
N = int(input())
S = input()

max_n = 0
n = 0
for s in S:
  if s == "I":
    n += 1
    if n > max_n:
      max_n = n
  else:
    n -= 1

print(max_n)
//  [python]
 = int(input())
s = input()
x = 0
l = [0]
for a in s:
    if a == "I":
        x = x + 1
        l.append(x)
    else:
        x = x - 1
        l.append(x)

print(max(l))
//  [python]
n = int(input())
ans = list(input())
count = 0
a = set()
for i in range(n):
    if ans[i] == 'I':
        count += 1
        a.add(count)
    elif ans[i] == 'D':
        count -= 1
        a.add(count)

print(max(a))
//  [python]
n = int(input())
ans = list(input())
count = 0

for i in range(n):
    if ans[i] == 'I':
        count += 1
    elif ans[i] == 'D':
        count -= 1
print(count + 1)
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String s = br.readLine();

        int cnt = 0;
        int max = 0;
        for(int i=0; i<n; i++){
            if('I' == s.charAt(i)){
                cnt++;
            } else if('D' == s.charAt(i)){
                cnt--;
            }

            if(max < cnt) max = cnt;
        }

        System.out.println(max);
    }
}
//  [java]
import java.io.*;

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {

		int N = nextInt();
		String S = nextString();

		long c=0;
		long ans = 0;
		for(int i=0;i<S.length();i++){
			if(S.charAt(i)=='I'){
				c++;
			}else{
				c--;
			}
			ans = Math.max(ans,c);
		}
		System.out.println(ans);
	}


	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}


}
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class Main {
    public static void main(String[] args){
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        String s = sc.next();
        int x = 0;
        int max = 0;
        for(int i=0; i<n; i++){
            Character character = s.charAt(i);
            if(character == 'I') x++;
            else x--;
            max = Math.max(max, x);
        }
        System.out.println(max);

    }

    static class FastScanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;
        private boolean hasNextByte() {
            if (ptr < buflen) {
                return true;
            }else{
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (buflen <= 0) {
                    return false;
                }
            }
            return true;
        }
        private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
        private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
        public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
        public String next() {
            if (!hasNext()) throw new NoSuchElementException();
            StringBuilder sb = new StringBuilder();
            int b = readByte();
            while(isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }
        public long nextLong() {
            if (!hasNext()) throw new NoSuchElementException();
            long n = 0;
            boolean minus = false;
            int b = readByte();
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            if (b < '0' || '9' < b) {
                throw new NumberFormatException();
            }
            while(true){
                if ('0' <= b && b <= '9') {
                    n *= 10;
                    n += b - '0';
                }else if(b == -1 || !isPrintableChar(b)){
                    return minus ? -n : n;
                }else{
                    throw new NumberFormatException();
                }
                b = readByte();
            }
        }
        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
            return (int) nl;
        }
        public double nextDouble() { return Double.parseDouble(next());}
    }
}
//  [java]

import java.util.*;
public class Main4 {
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		sc.nextLine();
		String st=sc.nextLine();
		int x=0;
		int ans=0;
		for(int i=0;i<n;i++)
		{
			if(st.charAt(i)=='I') x++;
			else x--;
			ans=Math.max(ans, x);
		}
		System.out.println(ans);
	}

}
//  [java]
import java.util.*;

public class Main {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        String s = sc.next();
        int ans = -1;
        int hagi = 0;
        for(int i=0;i<n;i++){
            
            
            if(s.charAt(i) == 'I'){
                hagi++;
            } else {
                hagi--;
            }
            
            ans =  Math.max(ans,hagi);
        }
        System.out.println(ans);
    }        
}
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n=scan.nextInt();
		String s=scan.next();
		int x=0;
		for (int i = 0; i < n; i++) {
			if(s.charAt(i)=='I') x+=1;
			else x-=1;
		}
		System.out.println(x+1);
	}
	

}
//  [cpp]
#include<cstdio>
#define max(a,b) (a>b?a:b)
char s[105];
int main()
{
	int n;
	scanf("%d\n%s",&n,s+1);
	int pos=0,ans=0;
	for(int i=1;i<=n;i++){
		if(s[i]=='I'){
			pos++;
			ans=max(ans,pos);
		}else if(s[i]=='D'){
			pos--;
		}
	}
	printf("%d\n",ans);
	return 0;
}
//  [cpp]
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
	char S[100];
	int i, N, x = 0, max = 0;
	scanf("%d%s", &N, &S);
	for (i = 0; i<N; i++) {
		if (S[i] == 73) {
			x += 1;
			if (x>max) {
				max = x;
			}
		}
		if(S[i]==68){
                       x-=1;
               }
	}
	printf("%d", max);
}
//  [cpp]
#include <cstdio>
#include <algorithm>
using namespace std;

int n;
char s[101];
int x, ans;

int main(){
	scanf("%d %s", &n, s);
	for(int i=0; i<n; ++i){
		if(s[i]=='I') ++x;
		else --x;
		ans = max(ans, x);
	}
	printf("%d\n", ans);
}
//  [cpp]
#include<iostream>

int main()
{
    int n,x=0,maxim;
    std::string str;
    std::cin>>n;
    std::cin.ignore();
    std::cin>>str;
    for(int i=0;i<n;i++){
        if(str[i]=='I')x++;
        else x--;
        if(i==0){
            maxim = x;
        }
        else if(x>maxim){
            maxim = x;
        }
    }
    std::cout<<maxim<<std::endl;
}
//  [cpp]
#include<bits/stdc++.h>

int main(){
 int n;
 cin >> n;
 string s;
 cin >> s;
  int ans = 0;
  int maxans = 0;
  for(int i = 0; i < n; i++){
    if(s[i] == 'I') ans ++;
    else ans--;
    maxans = max(ans,maxans);
  }
  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
// #include<atcoder/all>
// using namespace atcoder;
#define rep(i,n) for(int i=0;i<n;i++)
#define FOR(i,start,end) for(int i=start;i<=end;i++)
const int INF = 1001001001;
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
typedef long long ll;
const ll MOD=1000000007;
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<class T>auto MAX(const T& a) { return *max_element(a.begin(),a.end()); }
template<class T>auto MIN(const T& a) { return *min_element(a.begin(),a.end()); }
template<class T, class U>U SUM(const T& a, const U& v) { return accumulate(a.begin(),a.end(), v); }
template<class T, class U>U COUNT(const T& a, const U& v) { return count(a.begin(),a.end(), v); }
template<class T, class U>int LOWER(const T& a, const U& v) { return lower_bound(a.begin(),a.end(), v) - a.begin(); }
template<class T, class U>int UPPER(const T& a, const U& v) { return upper_bound(a.begin(),a.end(), v) - a.begin(); }
int GCD(int a, int b) { return b ? GCD(b, a%b) : a; }
int LCM(int a, int b) { int g = GCD(a, b); return a / g * b; }
typedef long double ld;
typedef unsigned long long int ull;
typedef pair<int,int> P;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int, int>> vpii;
typedef vector<pair<ll, ll>> vpll;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<vc> vvc;
typedef vector<vs> vvs;
typedef vector<vll> vvll;
typedef map<int, int> mii;
typedef set<int> si;
//---------------------------------------------------------------------------------------------------

int main(void){
    // Your code here!
    int n; cin >> n;
    string s; cin >> s;
    int ans = -1;
    int x = 0;
    rep(i,n) {
        if (s[i] == 'I') x++;
        else x--;
        if (ans < x) ans = x;
    }
    cout << ans << endl;
}
//  [c]
#include<stdio.h>
int main()
{
int i=0,n,x=0,max=0;
char ch[1000];
scanf("%d",&n);
scanf("%s",ch);
while(ch[i]!=NULL)
{
    if(ch[i]=='I')
    {
        x += 1;
    }
    else if(ch[i]=='D')
    {
        x -= 1;
    }
    
    if(x>max)
    {
        max=x;
    }
    i++;
}
printf("%d",max);

}
//  [c]
#include <string.h>
#include <stdio.h>

int main(void)
{
    int a,i,count = 0,we = 0;
    char b[100];
    scanf("%d%s",&a,b);
    for (i = 0; i < strlen(b); i++) {
        if (b[i] == 'I') {
            count++;
        }else{
            count--;
        }
        if (we < count) {
            we = count;
        }
    }
    printf("%d\n",we);
    return 0;
}
//  [c]
s,a,c;
main(){
  for(;getchar_unlocked()>10;);
  for(;(c=getchar_unlocked())>10;s=s<--a?a:s)a+=(c&1)<<1;
  printf("%d",s);
}
//  [c]
#include<stdio.h>
int main(){
  int n;
  scanf("%d\n",&n);
  char str[n+1];
  scanf("%s\n",str);
  int x=0,i,k,d=0;
  for(i=0;i<n;i++){
    if(str[i]=='I') x++;
    if(str[i]=='D') x--;
    k = x;
    if(k>d) d=k;
  }
  printf("%d\n",k);
  return 0;
}
//  [c]
#include<stdio.h>
int main(){
  int n;
  scanf("%d\n",&n);
  char str[n+1];
  int x=0,i;
  for(i=0;i<n;i++){
    if(str[i]=='I') x++;
    if(str[i]=='D') x--;
  }
  printf("%d\n",x);
  return 0;
}
//  [c]
#include<stdio.h>
int main(){
  int n;
  scanf("%d\n",&n);
  char str[n+1];
  int x,i;
  for(i=0;i<n;i++){
    if(str[i]=='I') x++;
    if(str[i]=='D') x--;
  }
  printf("%d\n",x);
  return 0;
}
//  [javascript]
// ABC052 B - Increment Decrement
'use strict'

function Main(input) {
    const tmp = input.trim().split('\n');
    const N = Number(tmp[0])
    const S = tmp[1].split('')
    // console.log(N, S);

    let result = 0;
    let x = 0;
    for (const v of S) {
        if (v === 'I') {
            x++;
        } else if (v === 'D') {
            x--;
        }
        if (x > result) {
            result = x;
        }
    }
    
    console.log(result);
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
'use strict'
const main = arg => {
	const input = arg.trim().split("\n");
	let N = input[0].split(' ')[0]
	let S = input[1].split(' ')[0]
	let Xs = []
	let x = 0
	Xs.push(x)
	for(let i = 0; i < N; i++) {
		if(S[i] === 'D') {
			Xs.push(--x)
		} else {
			Xs.push(++x)
		}
	}
	console.log(Math.max(...Xs))
}   
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict";
const main = arg => {
  let info = arg.split("\n");
  let max = 0;
  let tmp = 0;
  for(let t of info[1]){
    if(t == "I"){
      tmp += 1;
    } else {
      tmp -= 1;
    }
    if(max < tmp){
    	max = tmp;
    }
  }
  
  console.log(max);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main (input) {
  var args = input.split("\n");
  var ar = args[1].split("");
  var x = 0;
  var a = [0];
  for(var i = 0; i < ar.length; i++){
    if ar[i] === "I"
      x++;
      a.push(x);
    else
      x--;
      a.push(x);
  }
  
  var ans = Math.max.apply(null, a);
  console.log(ans);
}
 
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main (input) {
  var args = input.split("\n");
  var ar = args[1].split("");
  var x = 0;
  var a = [0];
  for(var i = 0; i < ar.length; i++){
    if arra[i] === "I"
      x++;
      a.push(x);
    else
      x--;
      a.push(x);
  }
  
  var ans = Math.max.apply(null, a);
  console.log(ans);
}
 
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main (input) {
  var args = input.split("\n");
  var arra = args[1].split("");
  var x = 0;
  var a = [0];
  for(var i = 0; i < arra.length; i++){
    if arra[i] === "I"
      x++;
      a[i + 1] = x;
    else
      x--;
      a[i + 1] = x;
  }
  
  var ans = Math.max.apply(null, a);
  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)

	var s string
	fmt.Scanf("%s", &s)

	res := 0
	x := 0
	for _, c := range s {
		if c == 'I' {
			x += 1
		}
		if c == 'D' {
			x -= 1
		}
		if res < x {
			res = x
		}
	}

	fmt.Println(res)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const mod = 1000000007

// 1MB
const ioBufferSize = 1 * 1024 * 1024

var sc = func() *bufio.Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	sc.Split(bufio.ScanWords)
	return sc
}()

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	n := nextInt()
	s := next()

	m, x := 0, 0
	for i := 0; i < n; i++ {
		switch s[i] {
		case 'I':
			x++
		case 'D':
			x--
		}

		if m < x {
			m = x
		}
	}

	fmt.Println(m)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

//Util
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

func absInt(a int) int {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func absFloat64(a float64) float64 {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a > b {
		return b
	} else {
		return a
	}
}

func str2Int(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	if x == 2 {
		return true
	}
	if x%2 == 0 {
		return false
	}

	b := true
	rootx := int(math.Sqrt(float64(x)))
	i := 3
	for i <= rootx {
		if x%i == 0 {
			b = false
			break
		}
		i += 2
	}
	return b
}

func PrimeFactors(n int) (pfs []int) {
	// Get the number of 2s that divide n
	for n%2 == 0 {
		pfs = append(pfs, 2)
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			pfs = append(pfs, i)
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs = append(pfs, n)
	}

	return
}

//Main
const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		return sc
	}()
)

var N int
var S string

func main() {
	sc.Split(bufio.ScanWords)

	N = nextInt()
	S = nextStr()

	var ans, now int
	for i := 0; i < N; i++ {
		if string(S[i]) == "I" {
			now++
			ans = maxInt(ans, now)
		} else {
			now--
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n, x, ans int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)
	for i := 0; i < n; i++{
		if s[i] == 'I'{
			x++
		} else {
			x--
		}
		ans = max(ans, x) 
	}
	fmt.Println(ans)
}

func max(a, b int) int {
	if a > b{
		return a
	} else {
		return b
	}
}
package main

import (
	"fmt"
)

func main() {
	var n, x, ans int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)
	for i := 0; i < n; i++{
		if s[i] == 'I'{
			x++
		} else {
			x--
		}
		ans = max(ans, x) 
	}
	fmt.Println(ans)
}

func max(a, b int) int {
	if a > b{
		return a
	} else {
		return b
	}
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n, x, ans int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)
	for i := 0; i < n; i++{
		if s[i] == 'I'{
			x++
		} else {
			x--
		}
		ans = max(ans, x) 
	}
}

func max(a, b int) int {
	if a > b{
		return a
	} else {
		return b
	}
}
//  [ruby]
n = gets.to_i
s = gets
m = 0
max = 0
for i in 0...n
  if s[i] == 'I'
    m += 1
    if m > max
      max = m
    end
  else
    m -= 1
  end
end

puts max
//  [ruby]
n = gets.to_i
s = gets.chomp
x = 0
ans = []
for i in 0..n-1
  if s[i] == "I"
    x += 1
    ans << x
  else
    x -= 1
    ans << x
  end
end

if ans.max < 0
  puts 0
else
  puts ans.max
end
//  [ruby]
N = gets.to_i
S = gets.chomp
x = 0
y = x
S.split('').each do |s|
    if s == 'I'
        x += 1
    else
        x -= 1
    end
    y = x if y < x
end
puts y
//  [ruby]
n = gets.to_i
s = gets.split('').map(&:to_s)
x = 0
px = 0
ans = 0
n.times do |i|
	px = x
	if s[i] == 'I'
		x+=1
	else
		x-=1 if x > 0
	end
	ans = x if px < x
end
puts ans
//  [ruby]
n = gets.to_i
s = gets.split('').map(&:to_s)
x = 0
px = 0
ans = 0
n.times do |i|
	px = x
	if s[i] == 'I'
		x+=1
	else
		x-=1
	end
	if x > px
		ans = x
	end
end
puts ans
//  [ruby]
n = gets.to_i
s = gets.split('').map(&:to_s)
x = 0
px = 0
ans = 0
n.times do |i|
	px = x
	if s[i] == 'I'
		x+=1
	else
		x-=1
	end
	ans = x if (px < x)
end
puts ans
//  [rust]
#![allow(non_snake_case)]
#![allow(unused_imports)]
use proconio::input;
use std::cmp::max;
use std::cmp::min;
use std::collections::HashMap;
use std::collections::VecDeque;

fn main() {
    input! {
        N: usize,
        S: String,
    }

    let mut x: i64 = 0;
    let mut ans: i64 = 0;

    for i in 0..N {
        let s: &str = &S[i..=i];
        if s == "I" {
            x += 1;
        } else {
            x -= 1;
        }

        ans = max(ans, x);
    }

    println!("{}", ans);
}
//  [rust]
use std::io;
use std::cmp::max;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let n:i32 = procon_read()[0];
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let mut s = buf.trim().chars().collect::<Vec<char>>();
	let mut x = 0;
	let mut maxi = 0;
	for i in s {
		if i == 'I' {
			x += 1;
		}else{
			x -= 1;
		}
		maxi = max(x, maxi);
	}
	println!("{}", maxi);
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// use std::io::{stdout, Write, BufWriter};
use std::cmp::{max};

fn main() {
    input! {
        n: usize,
        s: String,
    }
    println!("{}", max(0,
             s.chars().map(|c| if c == 'I' {1} else {-1}).collect::<Vec<i32>>().iter()
             .scan(0, |state, i| {
                 *state += i;
                 Some(*state)
             }).max().unwrap())
    )
}