jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
'use strict'
function main(input) {
    const tmp = input.split('\n');
    const NK = tmp.shift().split(' ').map((elem) => parseInt(elem, 10));
    const N = NK[0];
    const K = NK[1];

    let bucket = new Array(100030).fill(0);
    for (let ab of tmp) {
        const a = parseInt(ab.split(' ')[0], 10);
        const b = parseInt(ab.split(' ')[1], 10);
        bucket[a] += b;
    }


    let count = 0;
    for (let i = 0; i < bucket.length; i++) {
        count += bucket[i];
        if (count >= K) {
            console.log(i);
            break;
        }
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main(input) {
    var n, k, a, b, tmp, i, m = new Map(), keys=[], size, cnt = 0;
    tmp = input[0].split(" ");
    n = parseInt(tmp[0], 10);
    k = parseInt(tmp[1], 10);

    for (i = 0; i < n; i++) {
        tmp = input[1+i].split(" ");
        a = (parseInt(tmp[0], 10));
        b = (parseInt(tmp[1], 10));
        if(m.has(a)){
            m.set(a, m.get(a)+b);
        }else{
            m.set(a, b);
            keys.push(a);
        }
    }

    size = keys.length;
    keys.sort(function (self, other) {
        if (self < other) {
            return -1;
        } else if (self > other) {
            return 1;
        } else {
            return 0;
        }
    });
    for (i = 0; i < size; i++) {
        cnt += m.get(keys[i]);
        if(cnt >= k){
            console.log(keys[i]);
            break;
        }
    }
}

main(require("fs").readFileSync("/dev/stdin", "utf8").split("\n"));
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const K = parseInt(arg[0].split(" ")[1]);
    const numbers = arg.slice(1, N+1);
    
    const map = [];
    
    for(let i in numbers) {
        let temp = numbers[i].split(" ").map(n=>parseInt(n));
        
        let number = temp[0];
        let amount = temp[1];
        
        map.push({number: number, amount: amount})
    }
    
    map.sort((a,b)=>a.number - b.number);
    
    let sum = 0;
    let i   = 0;
    
    while(sum < K) {
        sum += map[i].amount;
        i++;
    }
    
    console.log(map[i - 1].number);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main(input) {
  input = myconv(input,3);
  var N = myconv(input[0],4)[0];
  var K = myconv(input[0],4)[1];
  var list = {};
  for(var i = 1; i <= N; i++){
    var a = myconv(input[i],4)[0];
    var b = myconv(input[i],4)[1];
    if(list[a] == null){
       list[a] = b;
    }else{
      list[a] += b;
    }
  }
  var set = Array.from(Object.keys(list)).sort(function(a,b){
  	return a-b;
  });
  for(var i = 0; i < set.length; i++){
    K -= list[set[i]];
    if(K <= 0){
       myout(set[i]);
      return;
    }
  }
}
Main(myin());
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func main() {
	sc.Split(bufio.ScanWords)
	n, k := ri(), ri()
	bk := make([]int, 1e5+1)
	var a, b int
	for i := 0; i < n; i++ {
		a, b = ri(), ri()
		bk[a] += b
	}
	acc := 0
	for i, v := range bk {
		acc += v
		if acc >= k {
			fmt.Println(i)
			return
		}
	}
}
//  [go]
package main

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

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	n, k := nextInt(), nextInt()
	cnt := make([]int, 100001)
	for i := 0; i < n; i++ {
		a, b := nextInt(), nextInt()
		cnt[a] += b
	}

	for i, sum := 1, 0; sum < k; i++ {
		sum += cnt[i]
		if sum >= k {
			puts(i)
			break
		}
	}
}

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

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

func nextInt() int {
	i, _ := strconv.Atoi(next())
	return i
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}
//  [go]
package main

import (
	"fmt"
	"os"
	"sort"
)

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

	count := map[int]int{}
	for i := 0; i < n; i++ {
		var a, b int
		fmt.Scanf("%d %d", &a, &b)
		count[a] += b
	}

	nums := []int{}
	for i, _ := range count {
		nums = append(nums, i)
	}

	sort.Ints(nums)

	sum := 0
	for _, i := range nums {
		sum += count[i]
		if sum >= k {
			fmt.Printf("%d\n", i)
			os.Exit(0)
		}
	}
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

type S struct {
	k, v int
}

func main() {
	var N, K int
	fmt.Scan(&N, &K)
	D := make(map[int]int)
	for i := 0; i < N; i++ {
		var a, b int
		fmt.Scan(&a, &b)
		D[a] += b
	}
	Ss := make([]S, len(D))
	idx := 0
	for k, v := range D {
		Ss[idx] = S{k: k, v: v}
		idx++
	}
	sort.Slice(Ss, func(i, j int) bool { return Ss[i].k < Ss[j].k })
	for i := 1; i < len(Ss); i++ {
		Ss[i].v += Ss[i-1].v
	}
	for _, s := range Ss {
		if K <= s.v {
			fmt.Println(s.k)
			return
		}
	}
	panic("あわわあわわわ、わぁ")
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func nextInt() int {
	var x int
	fmt.Scan(&x)
	return x
}

func main() {
	n := nextInt()
	k := nextInt()

	ps := make([]pair, n)
	for i := range ps {
		a := nextInt()
		b := nextInt()
		ps[i] = pair{a, b}
	}
	sort.Stable(pairs(ps))

	var ans int
	for k > 0 {
		ans = ps[0].x
		k -= ps[0].y
		ps = ps[1:]
	}
	fmt.Println(ans)
}

type pair struct{ x, y int }
type pairs []pair

func (ps pairs) Len() int           { return len(ps) }
func (ps pairs) Swap(i, j int)      { ps[i], ps[j] = ps[j], ps[i] }
func (ps pairs) Less(i, j int) bool { return ps[i].x < ps[j].x }
//  [ruby]
_, k, *v=`dd`.split.map &:to_i
m=[0]*(10**5+1)
v.each_slice(2){|a, b| m[a]+=b}
m.each.with_index(1){|x, i| (p i; break) if 0>=k-=m[i]}
//  [ruby]
_, k, *ab = `dd`.split.map{|t|t.to_i}

sz = 0

m = [0] * (10**5+1)

ab.each_slice(2){|(a,b)| m[a] += b }

m.each_with_index do |b,i|
  
  sz += b
  if k <= sz
    puts i
    exit
  end
end
//  [ruby]
n,k = gets.split.map!(&:to_i)

count = Array.new(10**5+1,0)
n.times do
    a,b = gets.split.map!(&:to_i)
    count[a] += b
end

min_k = 0
i = 0
while min_k < k
    min_k += count[i]
    i += 1
end

puts i-1
//  [ruby]
eval"_,B,*C="+`dd`.split*?,;C.each_slice(2).sort.any?{|x,y|p x if 0>=B-=y}
//  [ruby]
def make1d(n)
  a = Array.new(n)
  for i in 0..(n-1)
    a[i] = 0
  end
  a
end

def make2d(height,width)
  a = Array.new(height)
  for i in 0..(height-1)
    a[i] = make1d(width)
  end
  a
end
 def min(a, b)
   (a < b) ? a : b
 end

# version 1.4
# see http://lecture.ecc.u-tokyo.ac.jp/johzu/joho-kagaku/


n,k=gets.split.map(&:to_i)
s=make2d(n,2)
for i in 0..n-1
  a,b=gets.split.map(&:to_i)
  s[i][0]=a
  s[i][1]=b
end
s.sort!

sum=0
for i in 0..n-1
  sum=sum+s[i][1]
  if sum>=k
    puts s[i][0]
    break
  end
end
//  [ruby]
n, k = gets.chop.split(" ").map(&:to_i)
ans =
    Array.new(n) do
      Array.new(2)
    end
n.times do |i|
  ans[i][0], ans[i][1] = gets.chop.split(" ").map(&:to_i)
end

ans.sort!

n.times do |i|
  k = k - ans[i][1]
  if k <= 0
    puts ans[i][0]
    break
  end
end
//  [rust]
fn main() {
	proconio::input!{
		n: usize,
		k: usize,
	}

	let mut v: Vec<usize> = vec![0; 100000];
	for _i in 0..n {
		proconio::input!{
			a: usize,
			b: usize,
		}
		v[a-1] += b;
	}
	let mut count = 0;
	for i in 0..v.len() {
		count += v[i];
		if count >= k {
			println!("{}", i+1);
			return;
		}
	}
}
//  [rust]
use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        mut ab: [[usize; 2]; n],
    }
    ab.sort();
    debug!(ab);
    let mut end = 0;
    for i in 0..n {
        end += ab[i][1];
        if k <= end {
            println!("{}", ab[i][0]);
            return;
        }
    }

}
//  [rust]
fn solve() {
    let (n, mut k): (usize, usize) = (read::<usize>(), read::<usize>());
    let mut query: Vec<(usize, usize)> = vec![];
    for i in 0..n {
        let (a, b): (usize, usize) = (read::<usize>(), read::<usize>());
        query.push((a, b));
    }
    query.sort();
    let mut cur = 0;
    while let Some(v) = k.checked_sub(query[cur].1) {
        if v == 0 {
            break;
        }
        k = v;
        cur += 1;
    }
    println!("{}", query[cur].0);
}

fn main() {
    let stack_size = 104_857_600;
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

// =========
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};
#[allow(unused_imports)]
use std::process::exit;

#[allow(dead_code)]
const MOD: usize = 1000000007;

fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// =========
//  [swift]
let input = readLine()!.characters.split(" ").map{Int(String($0))!}
var arr = (0...100000).map{_ in 0}
for _ in 0..<input[0] {
  let input = readLine()!.characters.split(" ").map{Int(String($0))!}
  arr[input[0]] += input[1]
}
var tmp = input[1]
for i in 1...100000 {
  tmp -= arr[i]
  if tmp <= 0 {
    print(i)
    break
  }
}
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const [n, k] = input[0].split(" ").map(a => Number(a));
  const abs = input.slice(1).map(a => a.split(" ").map(b => Number(b)));
  const map = {};
  for (let i = 0; i < n; i++) {
    const [a, b] = abs[i];
    if (!map[a]) {
      map[a] = b;
    } else {
      map[a] += b;
    }
  }
  const keys = Object.keys(map).sort((a, b) => Number(a) - Number(b));
  let result = keys[keys.length - 1];
  let num = k;
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const cnt = map[key];
    if (num <= cnt) {
      result = key;
      break;
    }
    num -= cnt;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [python]
import numpy as np
K, N = map(int, input().split())
A = list(map(int, input().split()))
A = np.array(A)
ma = 0
for i in range(N-1):
  if A[i+1] - A[i] > ma:
    ma = A[i+1] -A[i]
if K -(A[N-1] -A[0]) > ma:
  ma = K -(A[N-1] -A[0])
print(K -ma)
//  [python]
K, N = map(int, input().split())
A = list(map(int, input().split()))

import numpy as np
diff = np.array(A[1:] + [K + A[0]]) - np.array(A)
print(K - diff.max())
//  [python]
import numpy as np
def main():
    k, n = map(int, input().split(" "))
    As = list(map(int, input().split(" ")))

    As = np.array(As)

    As_dists = As[1:] - As[:-1]
    #print(As_dists)
    As_dists = np.append(As_dists, As[0] + (k - As[-1]))
    max_dists = np.max(As_dists)
    #print(As_dists)
    #print(max_dists)

    ans = k - max_dists
    print(ans)

if __name__ == '__main__':
    main()
//  [java]
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int K=scan.nextInt();
        int N=scan.nextInt();
        List<Integer> houseDist=new ArrayList<Integer>();
        for(int i=0;i<N;i++){
            houseDist.add(scan.nextInt());
        }
        List<Integer> sortedDist = houseDist.stream().sorted().collect(Collectors.toList());
        List<Integer> betweenHouse = new ArrayList<Integer>();
        for(int i=1;i<N;i++){
            betweenHouse.add(sortedDist.get(i)-sortedDist.get(i-1));
        }
        betweenHouse.add(sortedDist.get(0)+(K-sortedDist.get(N-1)));
        int max = betweenHouse.stream().mapToInt(value -> value).max().getAsInt();
        int sum = betweenHouse.stream().mapToInt(value -> value).sum() - max;
        System.out.println(sum);
    }
}
//  [java]
import java.util.ArrayList;
import java.util.OptionalInt;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int K = sc.nextInt(),N =sc.nextInt();
	ArrayList<Integer> list = new ArrayList<>();
	for(int i=0;i<N;i++) {
		list.add(sc.nextInt());
	}
	ArrayList<Integer> sa = new ArrayList<>();
	for(int i=1;i<N;i++) {
		sa.add(list.get(i)-list.get(i-1));
	}
	sa.add(list.get(0)+K-list.get(N-1));
	OptionalInt max = sa.stream().mapToInt(v -> v).max();
	int ans = K-max.getAsInt();
	System.out.println(ans);
}
}
//  [java]
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		try (Scanner sc = new Scanner(System.in)) {
			int round = sc.nextInt();
			int houseNum = sc.nextInt();
			List<Integer> tmpLength = new ArrayList<Integer>(houseNum);
			for(int i=0; i<houseNum; i++) {
				tmpLength.add(sc.nextInt());
			}

			List<Integer> houseLength = new ArrayList<>(houseNum);
			for (int i = 0; i < tmpLength.size() - 1; i++) {
				houseLength.add(tmpLength.get(i + 1) - tmpLength.get(i));
			}
			int firstToLast = tmpLength.get(0) + (round - tmpLength.get(tmpLength.size() - 1));
			houseLength.add(firstToLast);
			
			OptionalInt max = houseLength.stream().mapToInt(i -> i.intValue()).max();
			int minLength  = houseLength.stream().mapToInt(i -> i.intValue()).sum() - max.getAsInt();
			System.out.println(minLength);
		}

	}
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define int     long long
#define F       first
#define S       second
#define _READ   freopen("input.txt","r", stdin);
#define _FAST   ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
void solve()
{
	int n,k;
	cin>>k>>n;
	vector<int> ar(2*k),prefix(2*k);
	for(int i=0;i<n;i++)
	{
		int temp;
		cin>>temp;
		temp%=k;
		ar[temp]=1;
		ar[temp+k]=1;
	}
	prefix[0]=ar[0];
	for(int i=1;i<2*k;i++)
		prefix[i]=prefix[i-1]+ar[i];
	// for(auto i:prefix)
	// 	cout<<i<<" ";
	// cout<<"\n";
	int ans=1e13;
	// ans,min length
	map<int,int> mp;
	for(int i=0;i<2*k;i++)
	{
		mp[prefix[i]]=i;
		if(prefix[i]>=n && mp.count(prefix[i]-n))
			ans=min(ans,i-mp[prefix[i]-n]);
	}
	//ans=min(ans,k-ans);
	cout<<ans-1;
}
int32_t main()
{
    //_READ
    int t;
    t=1;
    while(t--)
        solve();
    return 0;
}
/*
===FOR N-Dimensional Vector===
https://codeforces.com/blog/entry/76149
g++ -std=c++17 -Wshadow -Wall -g -fsanitize=address -fsanitize=undefined a.cpp -o a -D_GLIBCXX_DEBUG
*/
//  [cpp]
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;

int main() {
  int k,n;
  cin >> k >> n;
  vector<int> a(n);
  for (int i = 0;i<n;i++) {
    cin >> a[i];
  }
  int x = a[0]+k-a[n-1];
  vector<int> b(n-1);
  for(int i = 0;i<n-1;i++) {
    b[i] = a[i+1]-a[i];
  }
  sort(b.begin(),b.end());
  reverse(b.begin(),b.end());
  int y = b[0];
  cout << k-max(x,y) <<endl;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<time.h>
void printarray(int arr[], int n);
int partition(int arr[], int i, int j, int pivot)
{
    int l, r, k, t;
    l = i;
    r = j;
    while (l <= r)
    {
        while (l <= r && arr[l] <= pivot)
            {l++;}
        while (l <= r && arr[r] >= pivot)
            {r--;}
        if (l <= r)
        {
            t = arr[l];
            arr[l] = arr[r];
            arr[r] = t;
            l++;r--;
        }
    }
    k = l - 1;
    arr[i - 1] = arr[k];
    arr[k] = pivot;
    // printf("Pivot index : %d\n",k);
    // printarray(arr,n);
    return k;
}
void RQS(int arr[], int i, int j)
{
    int t, p, k;
    if (i < j)
    {   srand(time(0));
        p = (rand()%(j-i+1)) + i;
        // p = 1;
        t = arr[i];
        arr[i] = arr[p];
        arr[p] = t;
        k = partition(arr,i+1,j, arr[i]);
        RQS(arr, i,k - 1);
        RQS(arr, k + 1, j);
        // printarray(arr,n);
    }
}
void printarray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
int main()
{
    int ans,n,i,k;
    scanf("%d%d",&k,&n);
    int arr[n];
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    ans = k;
    int  j;
    i = 0;
    j = n-1;
    RQS(arr,i, j);
    for(i=0;i<n-1;i++)
    {
        if(ans > k - (arr[i+1]-arr[i]))
        {
            ans = k - (arr[i+1]-arr[i]);
        }
    }
    if(arr[n-1]-arr[0]<ans)
    {
        ans = arr[n-1]-arr[0];
    }
    printf("%d",ans);
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int cmp(const void *n1, const void *n2)
{
    return *(int *)n1 - *(int *)n2;
}

int main(void)
{

    int totalDistance, houseNum;
    
    scanf("%d%d", &totalDistance, &houseNum);

    int distance[houseNum];
    for (int index = 0; index < houseNum; index++)
    {
        scanf("%d", &distance[index]);
    }

    int moveDistance[houseNum * 2];
    for (int index = 0; index < houseNum * 2; index++)
    {
        if (index == 0)
        {
            moveDistance[index] = distance[houseNum - 1] - distance[index];
        }
        else if (index == (houseNum * 2) - 1)
        {
            moveDistance[index] = distance[houseNum - 1] - distance[0];
        }
        else if (index % 2 == 1)
        {
            moveDistance[index] = totalDistance - distance[index / 2] + distance[(index / 2) + 1];
        }
        else
        {
            moveDistance[index] = totalDistance - distance[index / 2] + distance[(index / 2) - 1];
        }
    }

    qsort(moveDistance, houseNum * 2, sizeof(int), cmp);

    printf("%d", moveDistance[0]);

}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef long long ll;

int hikaku(const void *n1,const void *n2)
{
    return *(int*)n1-*(int*)n2;
}

int main()
{
    int k,n,ans=0;
    scanf("%d %d",&k,&n);
    int a[n],b[n];

    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    
    qsort(a,n,sizeof(int),hikaku);
    for(int i=0;i<n-1;i++)
    {
        b[i]=a[i+1]-a[i];
    }
    b[n-1]=k-a[n-1]+a[0];

    qsort(b,n,sizeof(int),hikaku);

    ans=k-b[n-1];

    printf("%d\n",ans);
}
//  [javascript]
function Main(input){
	input = input.split("\n");
	var mem = input[0].split(" ").map(Number);
	var arr = input[1].split(" ").map(Number);
	var max = 0;
	for(var i=1;i<arr.length;i++){
	    if(max<arr[i]-arr[i-1]) max = arr[i]-arr[i-1];
	}
	if(mem[0]-arr[arr.length-1]+arr[0]>max) max = mem[0]-arr[arr.length-1]+arr[0];
	console.log(mem[0]-max)
}Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [javascript]
"use strict";
function main(input) {
  let kari = input[0].trim().split(" ").map(i => parseInt(i));
  let k = kari[0];
  let n = kari[1];

  let a = input[1].trim().split(" ").map(i => parseInt(i));

  let b = [];
  b[0] = 0;
  for(let i=1;i<n;i++){
    b[i] = a[i] - a[i-1];
  }
  b[n] = a[0] + (k - a[n-1]);
  //console.log(b);
  
  b.sort(function(a, b) {
    return b - a;
  });

  let sum = 0;

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

  console.log(sum)

}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));
//  [javascript]
    // inputに入力データ全体が入る
    function Main(input) {
      var input1 = input.split("\n")[0];
      var k = input1.split(" ")[0];
      k = parseInt(k, 10);
      var input2 = input.split("\n")[1];
      var a = input2.split(" ");
      var max = 0;
      for (var i=0; i< a.length;i++) {
        if ( i === a.length -1) {
          var sa = a[0] - a[i] + k;
          if ( sa > max) {
            max = sa;
          }
          break;
        }
        var sa =  a[i+1] - a[i];
        if (sa > max ) {
          max = sa;
        }
      }
      console.log(k - max);
    }
    //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"fmt"
)

//最大値
func Max(nums ...int) int {
	if len(nums) == 0 {
		panic("min() requires at least one arguments.")
	}
	res := nums[0]
	for _, val := range nums {
		if res < val {
			res = val
		}
	}
	return res
}


func main() {
	var k, n int
	fmt.Scan(&k, &n)
	a := make([]int, n)
	dist := make([]int, n+1)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}

	var ans int
	for i := 0; i < n-1; i++ {
		dist[i] = a[i + 1] - a[i]
		ans += dist[i]
	}
	dist[n] = a[0] + k - a[n - 1]
	ans += dist[n]
	fmt.Println(ans - Max(dist...))
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var k, n int
	fmt.Scan(&k, &n)
	as := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&as[i])
	}

	ds := make([]int, n)
	for i := 0; i < n-1; i++ {
		ds[i] = as[i+1] - as[i]
	}
	ds[n-1] = k - as[n-1] + as[0]

	mx := 0
	ans := 0
	for i := 0; i < n; i++ {
		ans += ds[i]
		mx = max(mx, ds[i])
	}
	ans -= mx
	fmt.Println(ans)
}

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

import (
	"fmt"
	"math"
)

func main() {
	var k, n int
	fmt.Scan(&k, &n)
	ai := make([]int, n)
	for a := 0; a < n; a++ {
		var tmp int
		fmt.Scan(&tmp)
		ai[a] = tmp
	}
	//maxroute
	min := k
	for r := 0; r < n; r++ {
		var tm int
		if len(ai)-1 == r {
			tm = k - ((k - ai[r]) + ai[0])
		} else {
			tm = (k + ai[r]) - ai[r+1]
		}
		if min > tm {
			min = tm
		}
	}
	fmt.Println(min)
}

//-------------------------------------------
// util tools

// abs 絶対値を返す
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// sliceInt []intをスライスする
func sliceInt(k int) []int {
	s := make([]int, getDigit(k))
	count := 0
	for k > 0 {
		i := k % 10
		s[len(s)-1-count] = i
		count++
		k = k / 10
	}
	return s
}

// sliceIntSum []intの合計を出す
func sliceIntSum(v []int) int {
	sum := 0
	for _, x := range v {
		sum += x
	}
	return sum
}

// reverse []intを反転
func reverse(s []int) []int {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return s
}

// getDigit intの桁数を取得
func getDigit(num int) int {
	digit := 0
	for num != 0 {
		num /= 10
		digit++
	}
	return digit
}

// getSumDigit intの各位の和を返す
func getSumDigit(num int) int {
	sum := 0
	for num != 0 {
		t := num % 10
		num /= 10
		sum += t
	}
	return sum
}

// lastPrime 素数 エラトステネスの篩
func lastPrime(max int64) int64 {
	if max <= 1 {
		return 2
	}
	primes := make([]int64, 1, max)
	primesF := make([]float64, 1, max)
	primes[0] = 2
	primesF[0] = 2.0

	count := int64(1)
	for n := int64(3); ; n += 2 {
		flag := true
		f := float64(n)
		rf := math.Sqrt(f)
		for i := 1; i < len(primes); i++ {
			if primesF[i] > rf {
				break
			} else if (n % primes[i]) == 0 {
				flag = false
				break
			}
		}
		if flag {
			count++
			if count >= max {
				return n
			}
			primes = append(primes, n)
			primesF = append(primesF, f)
		}
	}
}
//  [ruby]
k,n = gets.chomp.split().map(&:to_i)
a = Array.new
b = Array.new
a = gets.chomp.split.map(&:to_i)
for i in 0..n-2
  b[i] = a[i+1]-a[i]
end
b[n-1]=k-a[n-1]+a[0]
c = b.each_with_index.min(n-1).map{|i|i[1]}
sum = 0
c.each{|i|sum += b[i]}
puts sum
//  [ruby]
K, N = gets.split.map{|i|i.to_i}
A = gets.split.map{|i|i.to_i}
m = 0
N.times{|i|
    d = (A[i] - A[i - 1]) % K
    warn "d:%d" % d
    if d > m
        m = d
    end
}
puts K - m
//  [ruby]
eval'K,N,*A='+`dd`.split*?,
p K-[A[0]+K-A[-1],*(0..N-2).map{|i|A[i+1]-A[i]}].max
//  [rust]
use std::io::*;
use std::str::*;
use std::cmp::max;

fn read<T: FromStr>() -> Option<T> {
    let stdin = stdin();
    let s = stdin
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect::<String>();
    s.parse::<T>().ok()
}

fn main() {
    let k: usize = read().unwrap();
    let n: usize = read().unwrap();
    let mut a: Vec<usize> = Vec::new();
    for _ in 0..n {
        a.push(read().unwrap());
    }
    let mut max_dist = k - a[n - 1] + a[0];
    // let mut dist: Vec<usize> = Vec::new();
    for n_i in 1..n {
        max_dist = max(max_dist, a[n_i] - a[n_i - 1]);
    }
    println!("{:?}", k - max_dist);
}
//  [rust]
use text_io::*;
use std::collections::HashMap;
use std::process::exit;

fn main() {
    let k:usize = read!();
    let n:usize = read!();
    let mut a:usize = read!();
    let mut b:usize = 0;
    let mut c:usize = a;
    for i in 1..n-1 {
        let mut x:usize = read!();
        if b < x-a {
            b=x-a;
        }
        a = x;
    }
    let mut zz:usize = read!();
    if b < zz-a {
        b=zz-a;
    }
    if b<k-zz+c {
        b=k-zz+c;
    }
    println!("{}",k-b);
}
//  [typescript]
class NormalInput {
  input: string[];
  pointer: number;
  constructor(raw: string) {
    this.input = raw.split(/ |\n/);
    this.pointer = 0;
  }
  int = (): number => {
    const ret = parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  };
  str = (): string => {
    const ret = this.input[this.pointer];
    this.pointer++;
    return ret;
  };
  strs = (length: number): string[] => {
    let ret: string[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.str());
    }
    return ret;
  };
  ints = (length: number): number[] => {
    let ret: number[] = [];
    for (let i = 0; i < length; i++) {
      ret.push(this.int());
    }
    return ret;
  };
}
function rep(n: number) {
  let a = [];
  for (let i = 0; i < n; i++) a.push(i);
  return a;
}
function Main({ int, str, strs, ints }: NormalInput) {
  const [K, N] = ints(2);
  const A = ints(N);
  let min = A[N - 1] - A[0];
  rep(N - 1).forEach(i => {
    min = Math.min(min, K - A[i + 1] + A[i]);
  });
  console.log(min);
}

//DO NOT EDIT
Main(new NormalInput(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
const main = (input: string) => {
  const inputs = input.split('\n');
  const [rakeMeter, count] = inputs.shift().split(' ').map(v => Number(v));
  // console.log(rakeMeter, count);

  const housePoints = inputs[0].split(' ').map(v=>Number(v));
  let ans = 0;
  for(let i = 0; i < count; i += 1) {
    const currentPoint = housePoints[i];
    const nextPoint = (i+1 < count) ? housePoints[i + 1] : housePoints[0] + rakeMeter;

    const shift = nextPoint - currentPoint;
    // console.log(shift);

    ans = Math.max(ans, shift);
  }

  console.log(rakeMeter - ans);
  // 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 house = inputs[1].split(' ').map(Number);
  let max = 0;

  for (let i = 0; i < house.length; i++) {
    let span;
    if (!house[i + 1]) {
      span = lake - house[i] + house[0];
    } else {
      span = house[i + 1] - house[i];
    }
    max = Math.max(max, span);
  }

  console.log(lake - max);
}
//  [python]
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()


def main():
    n = II()
    s = S()
    r = 0
    t = 0
    for c in s:
        if c == 'I':
            t += 1
            if r < t:
                r = t
        else:
            t -= 1
    return r


print(main())
//  [python]
m,c,n = 0,0, raw_input()
for l in raw_input():
	c += 1 if l == 'I' else -1
	m = max(c,m)
print m
//  [python]
import numpy
N = input()
x = [0] + [1 if c == 'I' else -1 for c in raw_input()]
print max(numpy.cumsum(x))
//  [java]
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
//            while (true)// MAKE SURE TO REMOVE THIS
                solve(in);
        }
    }

    private static void solve(Scanner in) {
        int N = in.nextInt();
        String S = in.next();
        int x = 0;
        int max = 0;
        for (int i = 0; i < N; i++) {
            x += S.charAt(i) == 'I' ? 1 : (-1);
            max = max > x ? max : x;
        }
        System.out.println(max);
    }
}
//  [cpp]
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;

int main() {
  int a, sai = 0, x = 0;
  string b;
  cin >> a >> b;
  for(int i = 0; i < a; i++) {
    if(b[i] == 'I') {
      x++;
      if(sai < x) sai = x;
    }else {
      x--;
    }
  }
  cout << sai << endl;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    ll a,b,c,d;
    cin>>a;
    string s;
    cin>>s;
    ll sum=0;
    ll max1=0;
    for(int i=0;i<a;i++)
    {
        if(s[i]=='I')
        {
            sum++;
        }
        else
        {
            sum--;
        }
        max1=max(sum,max1);
    }
    cout<<max1<<endl;
    return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define fastio 			ios::sync_with_stdio(0);	cin.tie(0); cout.tie(0);  cout<<fixed;  cout<<setprecision(12);
#define randomINT 		mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define	newl 			cout<<"\n"
#define DISP(as)		for(auto it : as) cout<<it<<" ";newl;
#define all(x)         	(x).begin(),(x).end()
#define mset(x,val)    	memset(x,val,sizeof(x))
#define newl           	cout<<"\n"
#define pb             	push_back
#define mp             	make_pair
#define f 				first
#define s 				second
#define dline          cerr<<"///REACHED///\n";
#define deb1(x)        cerr<<#x<<" = "<<x<<'\n';
#define deb2(x,y)      cerr<<'['<<#x<<','<<#y<<"] = "<<'['<<x<<','<<y<<']'<<'\n';
#define deb3(x,y,z)    cerr<<'['<<#x<<','<<#y<<','<<#z<<"] = "<<'['<<x<<','<<y<<','<<z<<']'<<'\n';

typedef long long 				ll;
typedef long double 			ld;
typedef vector<ll> 				vll;
typedef pair<ll , ll> 			pll;
typedef pair<ld, ld> 			pld;
typedef unordered_map<ll, ll> 	um;
typedef vector<pll> 			vpll;

const ll 	MAX5 	= 	1e+5 + 7;
const ll 	MAX7 	= 	1e+7 + 7;
const ll 	MAXN 	= 	MAX7;
const ll   	INF   	=  	0x7f7f7f7f7f7f7f7f;
const int  	INFi 	=  	0x7f7f7f7f;
const ll 	MOD		=  	1e+9 + 7;

vll adj[MAXN]; ll visit[MAXN] = {};
int dx8[] = {0, 1, 1, 1, 0, -1, -1, -1}, dy8[] = {1, 1, 0, -1, -1, -1, 0, 1};
int dx4[] = {0, 1, 0, -1}, dy4[] = {1, 0, -1, 0};

// <------------- Declare Variables Here ------------> //

ll T = 1;
ll n, x, y, r, p;
string s, t;
// <------------- Implement Functions Here ----------> //



// <------------- Start of main() -------------------> //

void MAIN() {
	cin>>n>>s;
	ll maxi = 0,x = 0;

	for(auto ch : s) {
		if(ch == 'I') x++;
		else x--;
		maxi = max(maxi,x);
	}

	cout<<maxi;
}

int main() {
	fastio; randomINT;
	//cin>>t;
	while (T--) {
		MAIN();
	}
	return 0;
}
//  [c]
#include <stdio.h>
int main(void){
    int n;
    char s[100+5];
    scanf("%d", &n);
    scanf("%s", s);
    int ans=0, x=0;
    for(int i=0; i<n; i++){
        if(s[i]=='I')x++;
        else x--;
        if(x>ans)ans=x;
    }
    printf("%d\n", ans);
    return 0;
}
//  [c]
#include <stdio.h>
int main(void){
    int N, x=0, max=0;
    char S[101];
    scanf("%d%s", &N, S);
    for(int i=0; i<N; i++){
        if(S[i]=='I') x++;
        else if(S[i]=='D') x--;
        if(max<x) max=x;
    }
    printf("%d", max);
    return 0;
}
//  [c]
#include <stdio.h>
int main(){
int n,number=0,max=0;
scanf("%d",&n);
char array[n];
scanf("%s",array);
for (int i=0;array[i]!='\0';i++){
	if(array[i]=='I'){
		number++;
	}
	else if(array[i]=='D'){
		number--;
	}
	if(max<number){
		max=number;
	}
}
printf("%d\n",max);
return 0;
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");
	//文字列から10進数に変換するときはparseIntを使います
	//var length = parseInt(input[0], 10);
  var num = tmp[0];
  var base  = input[1];
  var arr= String(base).split('');
	//出力
  var x = 0;
  var max = 0;
  //var num = arr.length;

  for (var i = 0; i < num; i++) {
    if (arr[i]=="I") {
      x += 1;
      if (max >= x) {
        max = max;
      }else {
        max = x;
      }
    }else if (arr[i]=="D") {
      x -= 1;
      }
    }
	console.log('%d',max);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
var input = require('fs').readFileSync('/dev/stdin', 'utf8').split("\n");
var n = Number(input[0]);
var ans = 0;
var tmp = 0;
var tx = input[1].split("");
for(var i in tx){
    if(tx[i] == 'I'){
        tmp++;
    }else{
        tmp--;
    }
    ans = Math.max(ans,tmp);
}
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 len = Number(lines[0]);
 var s = lines[1].split('');
 var x = 0;
 var ar = [];
 ar.push(x);
 for(i=0; i<len; i++){
   if(s[i] == 'I'){
     x++;
     ar.push(x);
   }else if(s[i] == 'D'){
     x--;
     ar.push(x);
   }
 }

 console.log(Math.max(...ar));
});
//  [go]
package main

import "fmt"

func main() {
	// Code for B - Increment Decrement
	var N int
	var S string
	fmt.Scanf("%d\n%s", &N, &S)

	var x int = 0
	var max int = 0
	for i := 0; i < N; i++ {
		if S[i] == 'I' {
			x++
		} else {
			x--
		}

		if max < x {
			max = x
		}
	}
	fmt.Println(max)
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	s := nextStr()

	x := 0
	xmax := 0
	for i := 0; i < n; i++ {
		if s[i] == 'I' {
			x++
			xmax = max(xmax, x)
		} else {
			x--
		}
	}

	fmt.Println(xmax)

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

// ---- 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 (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	nextInt()
	S := nextBytes()

	x := 0
	m := 0

	for i := 0; i < len(S); i++ {
		if S[i] == 'I' {
			x++
		} else {
			x--
		}

		m = max(m, x)
	}

	fmt.Println(m)
}

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

var stdin = initStdin()

func initStdin() *bufio.Scanner {
	bufsize := 1 * 1024 * 1024 // 1 MB
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Buffer(make([]byte, bufsize), bufsize)
	stdin.Split(bufio.ScanWords)
	return stdin
}

func nextString() string {
	stdin.Scan()
	return stdin.Text()
}

func nextBytes() []byte {
	stdin.Scan()
	return stdin.Bytes()
}

func nextInt() int {
	i, _ := strconv.Atoi(nextString())
	return i
}

func nextInt64() int64 {
	i, _ := strconv.ParseInt(nextString(), 10, 64)
	return i
}

func debug(args ...interface{}) {
	fmt.Fprintln(os.Stderr, args)
}
//  [ruby]
N = gets.to_i
S = gets.chomp.split('')

max = 0
current = 0

S.each do |c|
  if c == 'I'
    current += 1
    max = current if max < current
  else
    current -= 1
  end
end

puts max
//  [ruby]
n = gets.to_i
smap = gets.chomp.chars

ans = 0
ansmap = []

smap.each do |s|
  if s == 'I'
    ansmap << ans + 1
    ans += 1
  else
    ansmap << ans - 1
	ans -= 1
  end
end

p ansmap.max > 0 ? ansmap.max : 0
//  [ruby]
n=gets.to_i
s=gets.chomp

ans=0
x=0
n.times do |i|
    if s[i]=="I"
        x+=1
    else
        x-=1
    end
    ans=[ans,x].max
end
puts ans
//  [rust]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("Failed to read bytes") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n:usize = read();
    let s:Vec<char> = read::<String>().chars().collect();
    let mut x = 0i64;
    let mut mx = 0;
    for i in s {
        if i == 'I' {
            x += 1;
        } else {
            x -= 1;
        }
        mx = std::cmp::max(x, mx);
    }
    println!("{}", mx);
}
//  [rust]
#[allow(unused_imports)]
use std::{cmp::Reverse, collections::*};

#[allow(unused_imports)]
use proconio::{
    fastout, input,
    marker::{Chars, Usize1},
};

#[allow(unused_imports)]
use itertools::Itertools;

#[allow(unused_imports)]
use num::Integer;

#[fastout]
pub fn main() {
    input! {
        _n: usize,
        s: Chars,
    }
    let mut x = 0;
    let mut max = 0;
    for c in s {
        if c == 'I' {
            x += 1;
            if max < x {
                max = x;
            }
        } else {
            x -= 1;
        }
    }
    println!("{}", max);
}
//  [rust]
#![allow(unused_imports)]
// use itertools::Itertools;
use proconio::{input, marker::*};

fn main() {
    input! {
        _n: usize,
        s: Chars
    };
    let mut max = 0;
    let mut x = 0;
    for c in s {
        x += match c {
            'I' => 1,
            'D' => -1,
            _ => unreachable!(),
        };
        max = std::cmp::max(max, x);
    }
    println!("{}", max);
}
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const S = input[1][0];

  let x = 0;
  let max = 0;

  S.split("").forEach((char) => {
    x = char === "I" ? x + 1 : x - 1;

    if (x > max) {
      max = x;
    }
  });

  return max;
};

console.log(main(read()));
//  [typescript]
"use strict";
const Main = (input) =>{
	let xs = input.trim().split('\n');
    let N = parseInt(xs[0]);
    let str = xs[1];
    let count = 0;
    let ans = [];
    for(let i=0; i<N; i++){
    	if (str.charAt(i) == 'I') {
			count++;
		}else if(str.charAt(i) == 'D') {
			count--;
		} 
        ans.push(count);
    }
    let max = Math.max(...ans);
    
    if(max<0){
      console.log(0);
    }else{
      console.log(max);
    }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));
//  [typescript]
"use strict";

const Main = args => {
  const input = args.trim().split("\n");
  const S = input[1].split("");
  let current = 0;
  let max = 0;

  S.forEach(e => {
    if (e === 'I') {
      current++;
    } else {
      current--;
    }
    max = current > max ? current : max
  });
  console.log(max);
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [python]
import math
import numpy as np


N = int(input())
S = list(input())

count = 0

for i in range(N):
    l1_l2_and = set(S[0:i+1]) & set(S[i+1::])
    if len(l1_l2_and) > count:
        count = len(l1_l2_and)

print(count)
//  [python]
N = int(input())
S = list(input())

for i in range(N):
  ans = 0
  for j in range(N):
    f = {}
    b = {}
    for k in range(j):
      if S[k] in f.keys():
        f[S[k]] += 1
      else:
        f[S[k]] = 1
        
    for k in range(N-j):
      if S[N-k-1] in b.keys():
        b[S[N-k-1]] += 1
      else:
        b[S[N-k-1]] = 1

    for k in range(N):
      common = 0
      for l in f.keys():
        if l in b.keys():
          common += 1
     
      if common > ans:
        ans = common
        
print(ans)
//  [python]
n=int(input())
s=input()
left=set()
ans=0

for i in range(n-1):
    left.add(s[i])
    right=set()
    for j in range(i+1,n):
        right.add(s[j])
    cnt=0
    for ll in left:
        if ll in right:
            cnt+=1
    ans=max(ans,cnt)

print(ans)
//  [java]
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        // long startTime = System.currentTimeMillis();

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        String s = scanner.next();

        scanner.close();

        System.out.println(resolve(n, s));

        // System.out.println(System.currentTimeMillis() - startTime);
    }

    private static int resolve(int n, String s) {

        int max = 0;
        String x, y;
        for (int i = 1; i < n; i++) {
            x = s.substring(0, i);
            y = s.substring(i, n);
            int count = compare(x, y);
            if (max < count) {
                max = count;
            }
        }
        return max;
    }

    private static int compare(String x, String y) {
        List<String> listX = Arrays.asList(x.split("")).stream().distinct().collect(Collectors.toList());
        List<String> listY = Arrays.asList(y.split("")).stream().distinct().collect(Collectors.toList());
        return (int) listX.stream().filter(listY::contains).count();
    }
}
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int num = Integer.parseInt(in.nextLine());
		String line = in.nextLine();
		List<Character> input = new ArrayList<>();
		for (int i = 0; i < num; ++i) {
			input.add(new Character(line.charAt(i)));
		}

		System.out.println(calc(input));

		in.close();

	}

	public static int calc(List<Character> input) {
		Set<Character> chars = new HashSet<>();
		chars.addAll(Arrays.asList(input.stream().distinct().toArray(Character[]::new)));
		int result = Integer.MIN_VALUE;
		for (int i = 1; i < input.size(); ++i) {
			int count = count(input.subList(0, i), input.subList(i, input.size()));
			if (count > result) {
				result = count;
			}
		}
		return result;
	}

	public static int count(List<Character> first, List<Character> last) {
		Set<Character> firstChars = new HashSet<>();
		firstChars.addAll(first);
		Set<Character> lastChars = new HashSet<>();
		lastChars.addAll(last);
		int result = 0;
		for (Character c : firstChars) {
			if (last.contains(c)) {
				result++;
			}
		}
		return result;
	}

}
//  [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();
		List<Integer> dupList = new ArrayList<>();


		for (int i=1; i<N; i++) {
			int dupNum=0;
			List<String> fHalfList = new ArrayList<String>(new HashSet<>(Arrays.asList(S.substring(0,i).split(""))));
			List<String> sHalfList = new ArrayList<String>(new HashSet<>(Arrays.asList(S.substring(i,N).split(""))));

			for (int j=0; j<fHalfList.size(); j++) {
				if (sHalfList.contains(fHalfList.get(j))) {
					dupNum++;
				}
			}
			dupList.add(dupNum);
		}

		Optional<Integer> max = dupList.stream().max((a, b) -> a.compareTo(b));

		System.out.println(max.orElse(0));
	}
}
//  [cpp]
/*
g++ -std=c++11 -o2 -Wall ABC098B.cpp -o ./out/ABC098B.out
./out/ABC098B.out
*/

#include <bits/stdc++.h>
using namespace std;

#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define present(c, e) ((c).find((e)) != (c).end())
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define tr(c, i) for (iter(c) != (c).begin(); i != (c).end(); ++i)
#define pb push_back
#define mp make_pair

typedef long long ll;

int xx[26];
int yy[26];

int main() {
//  freopen("./input/input.txt", "r", stdin);
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  string s;
  cin >> n;
  cin >> s;
  int ans = 0;
  for (int i = 1; i < n; ++i) {
    fill(xx, xx + 26, 0);
    fill(yy, yy + 26, 0);
    for (int j = 0; j < i; ++j) {
      int c = s[j] - 'a';
      ++xx[c];
    }
    for (int j = i; j < n; ++j) {
      int c = s[j] - 'a';
      ++yy[c];
    }
    int temp = 0;
    for (int k = 0; k < 26; ++k) {
      if (xx[k] > 0 && yy[k] > 0) {
          ++temp;
      }
    }
    ans = max(ans, temp);
  }
  cout << ans << "\n";
  return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define rep(i, n) for(int i=0; i<(n); ++i)
#define max  200001

//qsort(str, n, sizeof(int), up_comp);
int up_comp(const void *a, const void *b){return *(int*)a - *(int*)b;}
int down_comp(const void *a, const void *b){return *(int*)b - *(int*)a;}
int int_sort( const void * a , const void * b ) {return strcmp(( char * )a , ( char * )b );}
int count_digit(int a){int i=0;while(a!=0){a=a/10;i++;}return i;}
int euclid( int a, int b ){int temp;if(a<b){temp=a;a=b;b=temp;}if(b<1)return -1;if(a%b==0) return b;return euclid(b,a%b);}

int main(void){
    
    int n;
    char s[max];
    int cnt=0, mmax=INT_MIN;
    
    scanf("%d%s", &n, s);
    
    for (int i=0; i<n-1; i++) {
        int a[max]={0}, b[max]={0};
        cnt=0;
        for (int j=i+1; j<n; j++) {
            b[s[j]-97]++;
        }
        for (int k=0; k<i+1; k++) {
            a[s[k]-97]++;
        }
        rep(l, 26){
            if (a[l]!=0&&b[l]!=0) {
                cnt++;
                //printf("%d,", l);
            }
        }
        if (cnt>mmax) {
            mmax=cnt;
        }
    }
    
    printf("%d", mmax);
    
    return 0;
}


//s[i]-97;
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

int main(void){

    int N;

    scanf("%d", &N);

    char S[N+1];

    scanf("%s", S);

    int max = 0;

    for(int i = 0; i < N-1; i++){
        int x['z'-'a'+1], y['z'-'a'+1];
        for(int j = 0; j <= 'z'-'a'; j++){
            x[j] = 0;
            y[j] = 0;
        }
        for(int j = 0; j <= i; j++){
            x[S[j]-'a'] = 1;
        }
        for(int j = i+1; j < N; j++){
            y[S[j]-'a'] = 1;
        }
        int c = 0;
        for(int j = 0; j <= 'z'-'a'; j++){
            if(x[j] == 1 && y[j] == 1){
                c++;
            }
        }
        if(c > max){
            max = c;
        }
    }

    printf("%d\n", max);

    return 0;
}
//  [c]
#include<stdio.h>

int main(void)
{
  int n;
  char s[110];
  scanf("%d%s",&n,s);

  int i,j,a,b,ans=0,cnt;
  char c;
  for(i=1;i<n;i++){
    cnt=0;
    for(c='a';c<='z';c++){
      a = 0;  b = 0;
      for(j=0;j<i;j++){
        if(s[j]==c)
          a = 1;
      }
      for(j=i;j<n;j++){
        if(s[j]==c)
          b = 1;
      }
      if((a==1)&&(b==1))
        cnt++;
    }
    if(ans<cnt)
      ans = cnt;
  }

  printf("%d\n",ans);
  return 0;
}
//  [javascript]
function main(input) {
	var a = input.split('\n');
	var N = parseInt(a[0], 10);
	var S = a[1];
	var countmax = 0;
	for(i=1;i<N;i++){
		var S1 = S.slice(0,i);
		var S2 = S.slice(i,N);
		//console.log(S1);
		//console.log(S2);
		var count = 0;
		for(j=0;j<S1.length;j++){
			var t = 0;
			for(k=j+1;k<S1.length;k++){
				if(S1[j] === S1[k]){
					t = -1;
					break;
				}
			}
			if(t >= 0){
				for(k=0;k<S2.length;k++){
					if(S1[j] === S2[k]){
						t = 1;
						break;
					}
				}
				if(t === 1){
					count += 1;
				}
			}
			//console.log(count);
		}
		countmax = Math.max(countmax,count);
	}
	console.log(countmax);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function check(a,b){
	var c={},d=0;
	for(var i=0;i<a.length;i++){
		c[a[i]]=true;
	}
	for(var i=0;i<b.length;i++){
		if(c[b[i]]){
			c[b[i]]=false;
			d++
		}
	}
	return d;
}

function main(input) {
	var max=0;var a;
	var n=parseInt(input.split("\n")[0]);
	var s=input.split("\n")[1];
	for(var i=1;i<n;i++){
		a=check(s.substr(0,i), s.substr(i));
		if(a>max)max=a;
	}
	console.log(max)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));