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();
        int k = sc.nextInt();
        String s = sc.next();
        int rl = 0;
        for (int i=0;i<n-1;i++){
            if (s.charAt(i)=='R'&&s.charAt(i+1)=='L')rl++;
        }
        int happy = n-rl*2;
        if (s.charAt(0)=='L')happy--;
        if (s.charAt(n-1)=='R')happy--;
        if (rl==0)System.out.println(n-1);
        else if (rl<=k+1)System.out.println(happy+Math.max(rl*2-2,rl));
        else System.out.println(happy+(k-rl)*2);
    }
    public 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());}
    }
    public static class BasicMath {
        private final int MAX = 510000;
        private final int MOD = 1000000007;
        private final long[] fac = new long[MAX];
        private final long[] finv= new long[MAX];
        private final long[] inv = new long[MAX];
        public long factorial(long num){
            if (num<2)return 1;
            else return num*factorial(num-1);
        }
        public int arraySum(int[] array){
            int ans = 0;
            for (int value : array) ans += value;
            return ans;
        }
        public double log(double base,double antilogarithm){
            return Math.log(antilogarithm)/Math.log(base);
        }
        public long gcd(long x,long y){
            if (y==0)return x;
            else return gcd(y,x%y);
        }
        public long lcm(long x,long y){
            return x/gcd(x,y)*y;
        }
        public HashMap<Long,Long> factorization(long num){
            HashMap<Long,Long> hash = new HashMap<>();
            long n = num;
            long count = 2;
            while (n>1){
                while (n%count==0){
                    n/=count;
                    if (hash.containsKey(count))hash.put(count,hash.get(count)+1);
                    else hash.put(count,1L);
                }
                count++;
            }
            return hash;
        }
        public int sum(int[] num){
            int ans = 0;
            for (int i = 0; i < num.length;i++){
                ans += num[i];
            }
            return ans;
        }
        public int[] reduce(int small, int big){
            int ins = 2;
            while (ins<=small){
                if (small%ins==0&&big%ins==0){
                    small/=ins;
                    big/=ins;
                    ins = 2;
                }else {
                    ins++;
                }
            }
            return new int[]{small, big};
        }
        public int reduceCount(int small, int big){
            int ins = 2;
            int ans = 0;
            while (ins<=small){
                if (small%ins==0&&big%ins==0){
                    small/=ins;
                    big/=ins;
                    ins = 2;
                    ans++;
                }else {
                    ins++;
                }
            }
            return ans;
        }
        public int binarySearch(int[] array, int target){
            int pos = -1;
            int left = 0;
            int right = array.length-1;
            int middle;
            while (pos==-1&&left<=right){
                middle = (left+right)/2;
                if (array[middle]==target)pos=middle;
                else if (array[middle]>target)right=middle-1;
                else left=middle+1;
            }
            return pos;
        }
        public long modPow(long a, long n, long mod){
            long res = 1;
            while (n>0){
                if ((n&1)!=0)res = res*a%mod;
                a=a*a%mod;
                n >>= 1;
            }
            return res;
        }
        public long modinv(long a, long mod){return modPow(a,mod-2,mod);}
        public void COMinit(){
            fac[0]=1;
            fac[1]=1;
            finv[0]=1;
            finv[1]=1;
            inv[1]=1;
            for (int i=2;i<MAX;i++){
                fac[i]=fac[i-1]*i%MOD;
                inv[i]=MOD-inv[MOD%i]*(MOD/i)%MOD;
                finv[i]=finv[i-1]*inv[i]%MOD;
            }
        }
        public long COM(int n, int k){
            if (n<k)return 0;
            if (n<0||k<0)return 0;
            return fac[n]*(finv[k]*finv[n-k]%MOD)%MOD;
        }
        public long HCOM(int n, int k){
            return COM(n+k-1,k);
        }
    }
    public static class Queue{
        private final int max = 1000000;
        private final int[] queue = new int[max];
        private int tail = 0; private int head = 0;
        public void init(){this.head = 0; tail = 0;}
        public boolean isEmpty(){return (head==tail);}
        public boolean isFull(){return (head == (tail+1)%max);}
        public void enqueue(int v){
            if (isFull()){
                System.out.println("error: queue is full.");
                return;
            }
            queue[tail++] = v;
            if (tail == max) tail = 0;
        }
        public int dequeue(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return -1;
            }
            int res = queue[head];
            ++head;
            if (head == max) head = 0;
            return res;
        }
    }
    public static class Stack{
        private final int max = 100000;
        private final int[] stack = new int[max];
        private int top = 0;
        public boolean isEmpty(){return (top==0);}
        public boolean isFull(){return (top==max);}
        public void init(){top=0;}
        public void push(int v){
            if (isFull()){
                System.out.println("error: stack is full.");
                return;
            }
            stack[top++] = v;
        }
        public int pop(){
            if (isEmpty()){
                System.out.println("error: stack is empty");
                return -1;
            }
            return stack[--top];
        }
    }
    public static class Pair{
        private int A = 0;
        private int B = 0;
        Pair(int a,int b){
            A=a;
            B=b;
        }
        public void changeA(int a){A=a;}
        public void changeB(int b){B=b;}
        public void changeAB(int a,int b){A=a;B=b;}
        public static Comparator sortWithA = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Pair p = (Pair)o1;
                Pair q = (Pair)o2;
                if (p.A<q.A)return -1;
                else if (p.A==q.A)return 0;
                else return 1;
            }
        };
        public static Comparator sortWithB = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Pair p = (Pair)o1;
                Pair q = (Pair)o2;
                if (p.B<q.B)return -1;
                else if (p.B==q.B)return 0;
                else return 1;
            }
        };
    }
}


import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	static int[][] map;
	static int[][] directions8= {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
	static int[][] directions4= {{-1,0},{1,0},{0,-1},{0,1}};
	static int ans;
	static int[] parent;//union-find用
	static int[] rank;//union-find用

	public static void main(String[] args) throws IOException {
		//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		//		String W	 = in.readLine();
		//		int num = Integer.parseInt(W.split(" ")[0]);

		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int K = sc.nextInt();
		String S = sc.next();
		boolean[] happy= new boolean[N-1];
		int unHappy = 0;

		for(int i = 0;i<N-1 ; i++) {
			if(i==N-2) {
				happy[i]= (S.charAt(i)==S.charAt(i+1)) && S.charAt(i)=='L';
			}
			happy[i] = S.charAt(i)==S.charAt(i+1);
			if(!happy[i]) {
				unHappy++;
			}
		}
		ans = N - unHappy + 2*K-1;

				System.out.println(Integer.min(ans, N));
	}

	//BFS用に二つの配列を足し算する
	static int[] addArrayElms(int[] a, int[] b) {
		int[] c = new int[a.length];
		for(int i = 0; i < a.length; i++) {
			c[i] = a[i] + b[i];
		}
		return c;
	}

	//	//二分探索
	//k <= num となる最小の配列要素kのインデックスを返す
	static private int binarySearch(long num, long[] orderedArray){
		int lowerBorder = -1;
		int upperBorder = orderedArray.length;
		int mid;

		while(upperBorder - lowerBorder >1) {
			mid = (upperBorder + lowerBorder)/2;
			if(orderedArray[mid]<=num) {
				lowerBorder = mid;
			}else {
				upperBorder = mid;
			}
		}
		return lowerBorder;
	}

	//二分探索
	//k <= num となる最小のList要素kのインデックスを返す
	static private int binarySearch(long num, ArrayList<Long> orderedList){
		int lowerBorder = -1;
		int upperBorder = orderedList.size();
		int mid;

		while(upperBorder - lowerBorder >1) {
			mid = (upperBorder + lowerBorder)/2;
			if(orderedList.get(mid)<=num) {
				lowerBorder = mid;
			}else {
				upperBorder = mid;
			}
		}
		return lowerBorder;
	}

	//aとbの最小公倍数を求める
	public static int gcd(int a, int b) {
		return b == 0 ? a: gcd(b, a % b);
	}
	public static long gcd(long a, long b) {
		return b == 0 ? a: gcd(b, a % b);
	}

	//Union-Find用の配列を要素数nで初期化
	static void ufInit(int n){
		parent = new int[n];
		rank = new int[n];
	}

	//Union-Findの要素の最上位の親（グループ名）を返す
	static int ufFind(int a) {
		if(parent[a]==a) {
			return a;
		}else {
			return ufFind(parent[a]);
		}
	}

	//Union-Find木を連結する
	static void ufUnite(int a, int b) {
		a = parent[a];
		b = parent[b];

		if(a==b) {
			return;
		}
		if(rank[a] > rank[b]){
			parent[b]=a;
		}else {
			parent[a]=b;
			if(rank[a]==rank[b]) {
				rank[b]++;
			}
		}
	}

	static boolean ufSame(int a, int b) {
		return ufFind(a)==ufFind(b);
	}
}


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
public class Main{
    static Scanner scn = new Scanner(System.in);
    static FastScanner sc = new FastScanner();
    static PrintWriter ot = new PrintWriter(System.out);
    static Random rand = new Random();
    static long mod = 1000000007;
    static long modmod = mod * mod;
    static long inf = (long)1e17;
    static int[] dx = {0,1,0,-1};
    static int[] dy = {1,0,-1,0};
    static int[] dx8 = {-1,-1,-1,0,0,1,1,1};
    static int[] dy8 = {-1,0,1,-1,1,-1,0,1};
    static char[] dc = {'R','D','L','U'};
    static char[] c;
    public static void main(String[] args) {
        int n = scn.nextInt();
        int k = scn.nextInt();
        String s = scn.next();
        c = s.toCharArray();
        int count = 0;
        int lr = -1;
        int rl = -1;
        for(int i = 0; i < n-1; i++){
            if(c[i] == 'L' && c[i+1] == 'R'){
                if(lr == -1){lr = i+1;}
                else{
                    swap(lr, i);
                    count++;
                    lr = -1;
                    rl = -1;
                }
            }else if(c[i] == 'R' && c[i+1] == 'L'){
                if(rl == -1){rl = i+1;}
                else{
                    swap(rl, i);
                    count++;
                    rl = -1;
                    lr = -1;
                }
            }
            if(count == k){
                break;
            }
        }
        System.out.println(lr);
        if((lr != -1 || rl != -1) && count < k){
            if(lr != -1){
                swap(lr, n-1);
            }else if(rl != -1){
                swap(rl, n-1);
            }
        }
        int ans = 0;
        for(int i = 0; i < n-1; i++){
            if(c[i] == c[i+1]){
                ans++;
            }
        }
        System.out.println(ans);
    }

    public static void swap(int x, int y){
        while(x < y){
            char tmp = c[x];
            c[x] = c[y];
            c[y] = tmp;
            x++;
            y--;
        }
    }
}
class FastScanner {
    private final java.io.InputStream in = System.in;
    private final byte[] b = new byte[1024];
    private int p = 0;
    private int bl = 0;
    private boolean hNB() {
        if (p<bl) {
            return true;
        }else{
            p = 0;
            try {
                bl = in.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bl<=0) {
                return false;
            }
        }
        return true;
    }
    private int rB() { if (hNB()) return b[p++]; else return -1;}
    private static boolean iPC(int c) { return 33 <= c && c <= 126;}
    private void sU() { while(hNB() && !iPC(b[p])) p++;}
    public boolean hN() { sU(); return hNB();}
    public String next() {
        if (!hN()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = rB();
        while(iPC(b)) {
            sb.appendCodePoint(b);
            b = rB();
        }
        return sb.toString();
    }
    public char nextChar() {
    	return next().charAt(0);
    }
    public long nextLong() {
        if (!hN()) throw new NoSuchElementException();
        long n = 0;
        boolean m = false;
        int b = rB();
        if (b=='-') {
            m=true;
            b=rB();
        }
        if (b<'0'||'9'<b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0'<=b&&b<='9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1||!iPC(b)){
                return (m?-n:n);
            }else{
                throw new NumberFormatException();
            }
            b = rB();
        }
    }
    public int nextInt() {
        if (!hN()) throw new NoSuchElementException();
        long n = 0;
        boolean m = false;
        int b = rB();
        if (b == '-') {
            m = true;
            b = rB();
        }
        if (b<'0'||'9'<b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0'<=b&&b<='9') {
                n *= 10;
                n += b-'0';
            }else if(b==-1||!iPC(b)){
                return (int) (m?-n:n);
            }else{
                throw new NumberFormatException();
            }
            b = rB();
        }
    }
    public int[] nextInts(int n) {
    	int[] a = new int[n];
    	for(int i=0;i<n;i++) {
    		a[i] = nextInt();
    	}
    	return a;
    }
    public int[] nextInts(int n,int s) {
    	int[] a = new int[n+s];
    	for(int i=s;i<n+s;i++) {
    		a[i] = nextInt();
    	}
    	return a;
    }
    public long[] nextLongs(int n) {
    	long[] a = new long[n];
    	for(int i=0;i<n;i++) {
    		a[i] = nextLong();
    	}
    	return a;
    }
    public int[][] nextIntses(int n,int m){
    	int[][] a = new int[n][m];
    	for(int i=0;i<n;i++) {
    		for(int j=0;j<m;j++) {
    			a[i][j] = nextInt();
    		}
    	}
    	return a;
    }

    void nextIntses(int n,int[] ...m) {
    	int l = m[0].length;
    	for(int i=0;i<l;i++) {
    		for(int j=0;j<m.length;j++) {
    			m[j][i] = nextInt();
    		}
    	}
    }
    void nextLongses(int n,long[] ...m) {
    	int l = m[0].length;
    	for(int i=0;i<l;i++) {
    		for(int j=0;j<m.length;j++) {
    			m[j][i] = nextLong();
    		}
    	}
    }
}


#include <bits/stdc++.h>
using Int = long long int;
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    Int n, k;
    char s[100000];
    cin >> n >> k;
    cin >> s;

    Int cnt = 0;
    for(Int i=1; i<n; i++){
        if(s[i-1] == s[i]) cnt++;
    }
    cout << min(n-1, cnt + 2*k) << endl;
    return 0;
}


#include <stdio.h>
#include <algorithm>

using namespace std;

int main() {
	int n, k, batas, sum = 0;
	char s[100010];
	scanf("%d %d %s", &n, &k, s);
	for (int i = 0; i < n; i++) {
		batas = i;
		while (batas + 1 < n) {
			if (s[batas + 1] != s[batas])
				break;
			batas++;
		}
		sum += (batas - i);
		i = batas;
	}
	sum = min(n - 1, sum + k + k);
	printf("%d\n", sum);
	return 0;
}


#include<stdio.h>
#include<cmath>
#include<algorithm>
#include<functional>
using namespace std;
int main(void)
{
	int N, K;
	char s[200010];
	int count = 0,mcount=0;
	scanf("%d%d%s", &N, &K, s);
	for (int i = 0; i < N - 1; i++) {
		if (s[i] == s[i + 1]) {
			count++;
		}
		else {
			mcount++;
		}
	}
	if (2 * K <= mcount) {
		printf("%d", count + 2 * K);
		return 0;
	}
	else {
			printf("%d", count + mcount);
			return 0;
	}
}


#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 10;

int getResult(vector<int> nums){
    int n = nums.size();
    int maxx1 = nums[0];
    int maxx2 = nums[n-1];
    int res1 = 0,res2 = 0;
    for(int i = 1 ; i < n ; i ++){
        if(maxx1 < nums[i]){
            res1 ++;
        }
        maxx1 = min(maxx1,nums[i]);
    }
    for(int i = n-2; i >= 0 ; i --){
        if(maxx2 < nums[i]){
            res2 ++;
        }
        maxx2 = min(maxx2,nums[i]);
    }
    return min(res1,res2);
}

signed main(){
    int n,k;
    cin>>n>>k;
    string s;
    int res = 0;
    for(int i = 1 ; i < s.size(); i ++)
        if(s[i] == s[i-1]){
            res ++;
        }
    res = min(res+2*k,n-1);
    cout<<res<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxm=2e6+5;
char s[maxm];
int n,k;
signed main(){
    cin>>n>>k;
    scanf("%s",s+1);
    int ans=0;
    int cnt=0;
    for(int i=2;i<=n;i++){
        if(s[i]==s[i-1])ans++;
        else cnt++;
    }
    if(cnt%2==0){
        ans+=min(cnt/2,k)*2;
    }else{
        cnt--;
        ans+=min(cnt/2,k)*2;
        k-=cnt*2;
        if(k>0)ans++;
    }
    cout<<ans<<endl;
    return 0;
}


#include<stdio.h>
int max(int a, int b){
  return a > b ? a:b;
}
int main(void){
  int n,k;
  scanf("%d%d",&n,&k);
  char s[n+1];
  scanf("%s",&s);
  int two=0,one=0,ord=1;
  for(int i=1;i<n;i++){//孤立集団数をカウント
	if(s[i]!=s[i-1])ord++;
  }
 printf("%d",n-max((ord-2*k),1));
  return 0;
}


#include<stdio.h>
int main(){
  int n,k,count=0,max,i;
  scanf("%d%d",&n,&k);
  char s[n+1];
  scanf("%s",s);
  for(i=0;i<n;i++)
    if(s[i]==s[i+1])
      count++;
  max=count+2*k;
  if(n>max)
    printf("%d\n",max);
  else
    printf("%d\n",n-1);
  return 0;
}


#include <stdio.h>

int main(void) {

  long n,k;
	scanf("%ld %ld", &n, &k);
  char s[n+1];
  scanf("%s", s);
  char head = s[0];
  long count_other = 0;
  for (long i = 1; i < n; i++) {
    if (s[i-1] == head && s[i] != head) {
      count_other++;
    }
  }
  long happy;
  if (s[n-1] == head) {
    happy = n-1-(count_other)*2;
  } else {
    happy = n-(count_other)*2;
  }
  if (count_other <= k) {
    happy = n-1;
  } else {
    happy += k*2;
  }
  printf("%ld\n", happy);

  return 0;
}


#include <stdio.h>
#include <iostream>
#include <string.h>
char s[100010];
int a[100010];
int main()
{
	int n, k;
	int d = 0;
	scanf("%d", &n);
	scanf("%d\n", &k);
	gets(s);
	int i,  c;
	int b;
	int l;
	b = 0;
	c = 0;
	i = 0;
	while (i < n-1)
	{
		if (s[i] != s[i + 1])
		{
			a[b] = i + 1;
			if ((b>0)&&((b%2)!=0))
			{
				d = a[b-1];
				while (d < a[b])
				{
					s[d] = s[d - 1];
					d++;
				}
				c++;
				if (c >= k)
					break;
			}
			b++;
		}
		i++;
	}
	if (c < k)
	{
		d = a[b - 1];
		while (d < n)
		{
			s[d] = s[d - 1];
			d++;
		}

	}
	d = 0;
	l = 0;
	while (d < n - 1)
	{
		if (s[d] == s[d + 1])
			l++;
		d++;
	}
	printf("%d\n", l);
	return 0;
}


#include <stdio.h>
char s[100005];
int a[100005];
int main()
{
	int n, k;
	int d = 0;
	scanf("%d", &n);
	scanf("%d\n", &k);
	d = 0;
	gets(s);
	int i, j, c;
	int b;
	int l = 1;
	int ml[3] = { 0 };
	c = 0;

	b = 0;
	while (c < k)
	{
		i = 0;
		d = 1;
		b = 0;
		ml[0] = 0;
		ml[1] = 0;
		ml[2] = 0;
		j = 1;
		a[0] = 0;
		l = 0;
		while (i + 1 < n)
		{
			if (s[i] == s[i + 1])
			{
				if (j == 0)
				{
					j = 1;
					l++;
				}
				else
					l++;

			}
			else
			{
				a[d] = i;
				a[d + 1] = i + 1;
				if (b < 2)
				{
					b++;
					l++;
				}
				else
				{

					if (l > ml[0])
					{
						ml[0] = l;
						ml[1] = a[d - 4];
						ml[2] = a[d];
					}
					l = l - a[d - 3] + a[d - 5] + 1;
				}
				j = 0;
				d = d + 2;
			}
			i++;
		}
		if (b < 2)
		{
			d = 0;
			while (d < n - 1)
			{
				s[d + 1] = s[d];
				d++;
			}
			ml[0] = l;
		}
		else
		{
			d = ml[1];
			while (d < ml[2])
			{
				s[d + 1] = s[d];
				d++;
			}
		}
		c++;
	}
	d = 0;
	l = 0;
	while (d < n - 1)
	{
		if (s[d] == s[d + 1])
			l++;
		d++;
	}
	printf("%d\n", l);
	return 0;
}


#include <stdio.h>
char s[100000];
int a[100000];
int main()
{
	int n, k;
	int d = 0;
	scanf("%d", &n);
	scanf("%d\n", &k);
	d = 0;
	gets(s);
	int i, j, c;
	int b;
	int l = 1;
	int ml[3] = { 0 };
	c = 0;

	b = 0;
	while (c < k)
	{
		i = 0;
		d = 1;
		b = 0;
		ml[0] = 0;
		ml[1] = 0;
		ml[2] = 0;
		j = 1;
		a[0] = 0;
		l = 0;
		while (i + 1 < n)
		{
			if (s[i] == s[i + 1])
			{
				if (j == 0)
				{
					j = 1;
					l++;
				}
				else
					l++;

			}
			else
			{
				a[d] = i;
				a[d + 1] = i + 1;
				if (b < 2)
				{
					b++;
					l++;
				}
				else
				{

					if (l > ml[0])
					{
						ml[0] = l;
						ml[1] = a[d - 4];
						ml[2] = a[d];
					}
					l = l - a[d - 3] + a[d - 5] + 1;
				}
				j = 0;
				d = d + 2;
			}
			i++;
		}
		if (b < 2)
		{
			d = 0;
			while (d < n - 1)
			{
				s[d + 1] = s[d];
				d++;
			}
			ml[0] = l;
		}
		else
		{
			d = ml[1];
			while (d < ml[2])
			{
				s[d + 1] = s[d];
				d++;
			}
		}
		c++;
	}
	d = 0;
	l = 0;
	while (d < n - 1)
	{
		if (s[d] == s[d + 1])
			l++;
		d++;
	}
	printf("%d\n", l);
	return 0;
}


var obj = init();
Main();
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
function next(){return obj.next();}
function hasNext(){return obj.hasNext();}
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");}
function init(){
  var inputFile = myin();
  var returnObj = {
    "list" : inputFile, "index" : 0, "max" : inputFile.length,
    "hasNext" : function(){return (this.index < this.max);},
    "next" : function(){if(!this.hasNext()){return "";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(t){console.log(t);}//標準出力
function myerr(t){console.error(t);}//標準エラー出力
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す　1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
  var one = nextIntArray();
  var N = one[0];
  var K = one[1];
  var list = next();
  var count = 0;
  for(var i = 1; i < N; i++){
    if(list[i - 1] == list[i]){
      count++;
    }
  }
  myout(Math.min(N - 1, count + (K * 2)));
}


function Main(input) {
    input = input.split("\n");
    var nk = input[0].split(' ');
    var n = parseInt(nk[0], 10);
    var k = parseInt(nk[1], 10);
    var s = input[1];
    var block = 1;
    for(var i = 0; i < n-1; i++){

        block += (s[i] != s[i+1]) ? 1 : 0;
    }
    var happiness = Math.min(n-block+(2*k), n-1);

	console.log(happiness);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var k = o.a();
  var s = o.a(1);
  var t = s[0], x = 0;
  for(var i = 1; i < n; i++){
    if(t !== s[i]){
      t = s[i];
      x++;
    }
  }
  x = Math.max(0,x-k*2)
  return n-1-x;
}


'use strict';

function main(lines) {
  const [N, K] = lines[0].split(' ').map(Number);
  const S = lines[1];

  let s = shorten(S);
  // console.log(s);
  for (let i = 0; i < K; i++) {
    if (s.length === 1) break;
    s = s[0] + s.slice(3);
    // console.log(s);
  }
  const happiness = N - s.length;
  console.log(happiness);
}

function shorten(s) {
  let len = s.length;
  for (let i = 0; i < len;) {
    if (i !== len-1 && s[i] === s[i+1]) {
      s = s.slice(0, i+1) + s.slice(i+2);
      len--;
    } else {
      i++;
    }
  }
  return s;
}

function calcHappiness(s) {
  return s.length - shorten(s).length;
}

function runWithStdin() {
  let input = "";
  process.stdin.resume();
  process.stdin.setEncoding("utf8");

  process.stdin.on("data", v => {
    input += v;
  });
  process.stdin.on("end", () => {
    main(input.split("\n"));
  });
}
runWithStdin();


function SumAbs(i, tmp){
  var sum = 0;
  sum  = tmp[i]
  if(i+1<tmp.length){
    sum += tmp[i+1]
  }
  if(i+2<tmp.length){
    sum += tmp[i+2];
  }
  return sum;
}
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  const S = inputStr[0];
  //文字列Sを重み付けして配列に格納する。Lは正、Rは負とする。
  var tmp = [];
  var lst = S.substr(0,1)
  var cnt = 1;
  for(var i=1 ; i<N ; i++){
    if( S.substr(i,1) != S.substr(i-1,1) ){
      tmp.push(cnt);
      cnt = 0;
    }
    cnt += 1;
  }
  //最後の文字列確認
  if( cnt != 0){
      tmp.push(cnt);
  }
  //本体処理
  var ans = 0;
  var cnt = 0;
  if(tmp.length <= 2){
    ans = N-1;
  } else {
    //累積和処理
    for(var j=0 ; j<K ; j++){
      var last = SumAbs(0,tmp);
      var posi = 0;
      var i=1;
      while( i<tmp.length ){
        var now = SumAbs(1,tmp);
        if(last < now){
          last = now;
          posi = i;
        }
        i++
      }
      //配列の置き換え
      tmp.splice(posi,3,last);
      i = posi;
    }
    ans = tmp.reduce(function(a, b) {
              return a + b;
    });
    ans -= tmp.length;
  }
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function SumAbs(i, tmp){
  var sum = 0;
  sum  = Math.abs(tmp[i])
  if(i+1<tmp.length){
    sum += Math.abs(tmp[i+1])
  }
  if(i+2<tmp.length){
    sum += Math.abs(tmp[i+2]);
  }
  return sum;
}
function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  const S = inputStr[0];
  //文字列Sを重み付けして配列に格納する。Lは正、Rは負とする。
  var tmp = [];
  var lst = S.substr(0,1)
  var cnt = 1;
  for(var i=1 ; i<N ; i++){
    if( S.substr(i,1) != S.substr(i-1,1) ){
      tmp.push(cnt);
      cnt = 0;
    }
    cnt += 1;
  }
  //最後の文字列確認
  if( cnt != 0){
      tmp.push(cnt);
  }
  //本体処理
  var ans = 0;
  var cnt = 0;
  if(tmp.length <= 2){
    ans = N-1;
  } else {
    //累積和処理
    for(var j=0 ; j<K ; j++){
      var last = SumAbs(0,tmp);
      var posi = 0;
      var i=1;
      while( i<tmp.length ){
        var now = SumAbs(i,tmp);
        if(last < now){
          last = now;
          posi = i;
        }
        i++
      }
      //配列の置き換え
      tmp.splice(posi,3,last);
      i = posi;
    }
    ans = tmp.reduce(function(a, b) {
              return a + b;
    });
    ans -= tmp.length;
  }
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	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 getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(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
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)
	k := getNextInt(scanner)
	s := getNextString(scanner)

	ans := 0

	for i := 1; i < n; i++ {
		if s[i-1] == s[i] {
			ans++
		}
	}

	fmt.Fprintln(writer, minint(ans+k*2, n-1))
	writer.Flush()
}

func minint(a int, b int) int {
	if a < b {
		return a
	}
	return b
}


package main

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

func solve() {
	n, k := getInt(), getInt()
	s := []rune(getString())

	cnt := 0
	sum := 0
	now := ' '
	for i, r := range s {
		if r != now {
			now = r
			sum += cnt
			cnt = 0
		} else {
			cnt++
			if i == n-1 {
				sum += cnt
			}
		}
	}

	ans := min(n-1, sum+(2*k))
	fmt.Fprintln(wr, ans)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// -----------------------------------------

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

func main() {
	buf := 200001
	sc.Buffer(make([]byte, buf), buf)
	sc.Split(bufio.ScanWords)
	solve()
	wr.Flush()
}

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

func getIntSlice(n int) []int {
	is := make([]int, n)
	for i := range is {
		is[i] = getInt()
	}
	return is
}

func getString() string {
	sc.Scan()
	s := sc.Text()
	return s
}


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 := r.nextInt(), r.nextInt()
	r.Scan(true)
	s := r.nextString()

	cnt := 0

	for i, end := 0, len(s); i < end; i++ {

		if i+1 < end && s[i] == s[i+1] {
			cnt++
		}
	}

	cnt += k * 2
	if cnt > len(s)-1 {
		cnt = len(s) - 1
	}
	fmt.Fprintln(stdout, cnt)
}


package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	var s []byte
	fmt.Scan(&s)
	p := s[0]
	cnt := 1
	var ans int
	for i := 1; i < n; i++ {
		if s[i] != p {
			cnt++
		} else {
			ans++
		}
		p = s[i]
	}
	if cnt == 1 {
		fmt.Println(ans)
		return
	}
	cnt -= 2
	if cnt%2 == 1 {
		ans += min((cnt+1)/2, k) * 2
	} else {
		if k >= cnt {
			ans += cnt / 2 * 2
			if k-cnt/2 > 0 {
				ans++
			}
		} else {
			ans += k * 2
		}
	}
	fmt.Println(ans)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

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

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


package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	var s []byte
	fmt.Scan(&s)
	p := s[0]
	cnt := 1
	var ans int
	for i := 1; i < n; i++ {
		if s[i] != p {
			cnt++
		} else {
			ans++
		}
		p = s[i]
	}
	if cnt == 1 {
		fmt.Println(ans)
		return
	}
	cnt -= 2
	if cnt%2 == 1 {
		ans += min((cnt+1)/2, k) * 2
	} else {
		if k >= cnt {
			ans += cnt / 2 * 2
			if k-cnt > 0 {
				ans++
			}
		} else {
			ans += k * 2
		}
	}
	fmt.Println(ans)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

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

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


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

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

// min, max, asub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

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

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

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 1000000)
	N, K := getInt(), getInt()
	s := getString()
	cur := s[0]
	cnt := 0
	for i := 1; i < N; i++ {
		// out(cnt, K, string(s[i]), string(cur))
		if s[i] == cur {
			cnt++
			continue
		}
		if K > 0 {
			cnt++
			cur = s[i]
			for i < N {
				if s[i] != cur {
					break
				}
				i++
				cnt++
			}
			K--
		}
		if i < N {
			cur = s[i]

		}
	}
	out(cnt)
}


class Array
  def score_abc140
    n = size
    self << 0
    res = 0
    n.times{|i| res += 1 if self[i+1] == self[i] }
    res
  end
end

n, k = gets.to_s.split.map{|t| t.to_i }
s = gets.chomp.bytes

puts [ s.score_abc140 + 2 * k, n - 1].min


# frozen_string_literal: true

N, K = gets.chomp.split(' ').map(&:to_i)
S = gets.chomp

cnt = 0
pre_string = nil
S.each_char do |string|
  cnt += 1 if string == pre_string

  pre_string = string
end

puts [cnt + (K * 2), N - 1].min


n,k = gets.split.map(&:to_i)
s = gets.chomp!

count = 1
pre = s[0]
s.each_char do |c|
    next if c == pre
    count += 1
    pre = c
end

if count <= 2*k then
    ans = n - 1
else
    ans = n + 2*k - count
end

puts ans


n, k = gets.split.map(&:to_i)
s = gets.chomp

ans = 0
c_l2r = 0
c_r2l = 0
n.times do |i|
    if s[i] == "R"
        next if i == n - 1
        ans += 1 if s[i+1] == "R"
    else
        next if i == 0
        ans += 1 if s[i-1] == "L"
    end
    next if i == 0
    if s[i] != s[i-1]
        if s[i] == "R"
            c_l2r += 1
        else
            c_r2l += 1
        end
    end
end

if c_l2r > c_r2l
    c_l2r, c_r2l = c_r2l, c_l2r
end

ans += 2*[k, c_l2r].min
k -= c_l2r
if k > 0 and c_r2l > c_l2r
    ans += 1
end

puts ans


io = STDIN
n,k=io.gets.split.map(&:to_i)
str=io.gets.chomp
pat=str.each_char.slice_when{|a,b|a!=b}.map(&:size)
cnt_1over= pat.select{|i|i>1}.size
init_point= pat.select{|i|i>1}.inject(:+)-cnt_1over
if (pat.size-2 >= k)
  puts init_point+k*2
else           #if (pat.size == k)
  puts str.size-1
end


io = STDIN
n,k=io.gets.split.map(&:to_i)
str=io.gets.chomp
pat=str.each_char.slice_when{|a,b|a!=b}.map(&:size)
cnt_1over= pat.select{|i|i>1}.size
init_point= pat.select{|i|i>1}.inject(:+)-cnt_1over
if (pat.size-2 >= k)
  puts init_point+k*2
elsif (pat.size-1 == k)
  puts init_point+(k-1)*2+1
else           #if (pat.size == k)
  puts init_point+(pat.size-1)*2
end


fn read_stdin() -> String {
    use std::io::Read;
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).unwrap();
    input
}

fn scan<'a, I: Iterator<Item = &'a str>, T: std::str::FromStr>(tokens: &mut I) -> T {
    tokens.next().unwrap().parse().ok().unwrap()
}

fn main() {
    let input = read_stdin();
    let tokens = &mut input.split_whitespace();
    let n: usize = scan(tokens);
    let k: usize = scan(tokens);
    let s: String = scan(tokens);
    let s = s.into_bytes();
    let mut cnt = 0;
    for i in 0..n - 1 {
        if s[i] == s[i + 1] {
            cnt += 1;
        }
    }
    println!("{}", std::cmp::min(n - 1, cnt + 2 * k));
}


fn main() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let k: usize = iter.next().unwrap().parse().unwrap();

    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let s = buf.trim().chars().collect::<Vec<char>>();

    let mut s_n = Vec::new();
    let mut prev_c = s[0];
    let mut cnt_c = 1;
    for &c in s[1..].iter() {
        if c != prev_c {
            s_n.push(cnt_c);
            prev_c = c;
            cnt_c = 1;
        } else {
            cnt_c += 1;
        }
    }
    s_n.push(cnt_c);

    let nr_part = 2 * k + 1;

    let mut ans = 0;

    if nr_part >= s_n.len() {
        ans = n - 1;
    } else {
        /*
        let mut sum = s_n[..nr_part].iter().fold(0, |s, &x| s+x);
        ans = sum;
        for i in nr_part..s_n.len() {
            sum = sum + s_n[i] - s_n[i-nr_part];
            ans = std::cmp::max(ans, sum);
        }
        */
        let sum = s_n.iter().fold(0, |s, &x| s+x-1);
        ans = sum + 2 * k;
    }

    println!("{}", ans);
}


fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

enum Direction {
    Left,
    Right,
}

fn main() {
    use Direction::*;

    let input = read_vec::<usize>();
    let (_n, k) = (input[0], input[1]);
    let chars = read::<String>().chars().collect::<Vec<_>>();

    let mut count = 0;
    let mut rl = 0;
    let mut lr = 0;

    let mut prev: Option<Direction> = None;
    for c in chars {
        match c {
            'R' => {
                match prev {
                    Some(Left) => {
                        lr += 1;
                    },
                    Some(Right) => {
                        count += 1;
                    }
                    None => {}
                }
                prev = Some(Right);
            },
            'L' => {
                match prev {
                    Some(Left) => {
                        count += 1;
                    },
                    Some(Right) => {
                        rl += 1;
                    },
                    None => {}
                }
                prev = Some(Left);
            },
            _ => {},
        }
    }

    for _ in 0..k {
        if lr > 0 && rl > 0 {
            lr -= 1;
            rl -= 1;
            count += 2;
        } else if lr > 0 {
            lr -= 1;
            count += 1;
        } else if rl > 0 {
            rl -= 1;
            count += 1;
        } else {
            break;
        }
    }

    println!("{}", count);
}


#![allow(unused_mut)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($y: expr),+) => {
        cmp::max($x, max!($($y),+))
    };
}

macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($y: expr),+) => {
        cmp::min($x, min!($($y),+))
    };
}

macro_rules! abs {
    ($x:expr, $y:expr) => {
        cmp::max($x, $y) - cmp::min($x, $y)
    };
}

const MOD: usize = 1_000_000_007;

struct BinCoeff {
    size: usize,
    fac: Vec<usize>,
    finv: Vec<usize>,
    inv: Vec<usize>,
}

impl BinCoeff {
    fn new(size: usize) -> BinCoeff {
        let fac = vec![0; size];
        let finv = vec![0; size];
        let inv = vec![0; size];
        let mut bincoeff = BinCoeff {
            size,
            fac: fac,
            finv: finv,
            inv: inv,
        };
        bincoeff.com_init();
        bincoeff
    }

    fn com_init(&mut self) {
        let fac = &mut self.fac;
        let finv = &mut self.finv;
        let inv = &mut self.inv;
        let size = self.size;
        fac[0] = 1;
        fac[1] = 1;
        finv[0] = 1;
        finv[1] = 1;
        inv[1] = 1;
        for i in 2..size {
            fac[i] = fac[i - 1] * i % MOD;
            inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
            finv[i] = finv[i - 1] * inv[i] % MOD;
        }
    }

    fn bin_coeff(&mut self, n: usize, k: usize) -> usize {
        if k > n / 2 {
            self.bin_coeff(n, n - k)
        } else {
            self.fac[n] * (self.finv[k] * self.finv[n - k] % MOD) % MOD
        }
    }
}

struct UnionFind {
    par: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> UnionFind {
        UnionFind {
            par: (0..size).collect::<Vec<usize>>(),
        }
    }

    fn root(&mut self, node: usize) -> usize {
        let parent = self.par[node];
        if parent == node {
            parent
        } else {
            let parent = self.root(parent);
            self.par[node] = parent;
            parent
        }
    }

    fn unite(&mut self, a: usize, b: usize) {
        let root_a = self.root(a);
        let root_b = self.root(b);
        self.par[root_b] = root_a;
    }

    fn is_same(&mut self, a: usize, b: usize) -> bool {
        let root_a = self.root(a);
        let root_b = self.root(b);
        root_a == root_b
    }
}

// must input n <= m
fn gcd(n: usize, m: usize) -> usize {
    if n == 0 {
        m
    } else {
        gcd(m % n, n)
    }
}

fn printer<T, U>(mut array: T)
where
    T: Iterator<Item = U>,
    U: fmt::Display + Copy,
{
    if let Some(a) = array.next() {
        print!("{}", a);
    }
    for a in array {
        print!(" {}", a);
    }
    println!()
}

fn sieve_of_eratosthenes(max: usize) -> Vec<bool> {
    let mut candidates = vec![true; max + 1];
    candidates[0] = false;
    candidates[1] = false;
    let mut num = 2;
    while num * num <= max {
        if candidates[num] {
            let prime = num;
            for n in 2..max / prime + 1 {
                candidates[prime * n] = false;
            }
        }
        num += 1;
    }
    candidates
}

use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{self, BufRead, Read};
use std::{cmp, fmt, iter, usize};

fn main() {
    input! {
        N: usize,
        K: usize,
        S: chars,
    }
    let count = 1 + S.windows(2).filter(|c| c[0] != c[1]).count();
    let unhappy = 1 + count.saturating_sub(2 * K);
    println!("{}", S.len() - unhappy);
}


#![allow(unused_mut)]
#![allow(non_snake_case)]
#![allow(unused_variables)]
#![allow(unused_imports)]
#![allow(unused_macros)]
#![allow(dead_code)]
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($y: expr),+) => {
        cmp::max($x, max!($($y),+))
    };
}

macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($y: expr),+) => {
        cmp::min($x, min!($($y),+))
    };
}

macro_rules! abs {
    ($x:expr, $y:expr) => {
        cmp::max($x, $y) - cmp::min($x, $y)
    };
}

const MOD: usize = 1_000_000_007;

struct BinCoeff {
    size: usize,
    fac: Vec<usize>,
    finv: Vec<usize>,
    inv: Vec<usize>,
}

impl BinCoeff {
    fn new(size: usize) -> BinCoeff {
        let fac = vec![0; size];
        let finv = vec![0; size];
        let inv = vec![0; size];
        let mut bincoeff = BinCoeff {
            size,
            fac: fac,
            finv: finv,
            inv: inv,
        };
        bincoeff.com_init();
        bincoeff
    }

    fn com_init(&mut self) {
        let fac = &mut self.fac;
        let finv = &mut self.finv;
        let inv = &mut self.inv;
        let size = self.size;
        fac[0] = 1;
        fac[1] = 1;
        finv[0] = 1;
        finv[1] = 1;
        inv[1] = 1;
        for i in 2..size {
            fac[i] = fac[i - 1] * i % MOD;
            inv[i] = MOD - inv[MOD % i] * (MOD / i) % MOD;
            finv[i] = finv[i - 1] * inv[i] % MOD;
        }
    }

    fn bin_coeff(&mut self, n: usize, k: usize) -> usize {
        if k > n / 2 {
            self.bin_coeff(n, n - k)
        } else {
            self.fac[n] * (self.finv[k] * self.finv[n - k] % MOD) % MOD
        }
    }
}

struct UnionFind {
    par: Vec<usize>,
}

impl UnionFind {
    fn new(size: usize) -> UnionFind {
        UnionFind {
            par: (0..size).collect::<Vec<usize>>(),
        }
    }

    fn root(&mut self, node: usize) -> usize {
        let parent = self.par[node];
        if parent == node {
            parent
        } else {
            let parent = self.root(parent);
            self.par[node] = parent;
            parent
        }
    }

    fn unite(&mut self, a: usize, b: usize) {
        let root_a = self.root(a);
        let root_b = self.root(b);
        self.par[root_b] = root_a;
    }

    fn is_same(&mut self, a: usize, b: usize) -> bool {
        let root_a = self.root(a);
        let root_b = self.root(b);
        root_a == root_b
    }
}

// must input n <= m
fn gcd(n: usize, m: usize) -> usize {
    if n == 0 {
        m
    } else {
        gcd(m % n, n)
    }
}

fn printer<T, U>(mut array: T)
where
    T: Iterator<Item = U>,
    U: fmt::Display + Copy,
{
    if let Some(a) = array.next() {
        print!("{}", a);
    }
    for a in array {
        print!(" {}", a);
    }
    println!()
}

fn sieve_of_eratosthenes(max: usize) -> Vec<bool> {
    let mut candidates = vec![true; max + 1];
    candidates[0] = false;
    candidates[1] = false;
    let mut num = 2;
    while num * num <= max {
        if candidates[num] {
            let prime = num;
            for n in 2..max / prime + 1 {
                candidates[prime * n] = false;
            }
        }
        num += 1;
    }
    candidates
}

use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{self, BufRead, Read};
use std::{cmp, fmt, iter, usize};

fn main() {
    input! {
        N: usize,
        K: usize,
        S: chars,
    }
    let S: Vec<char> = S;
    let mut counts = Vec::new();
    let mut count = 0;
    for (c, n) in S.iter().zip(S.iter().skip(1)) {
        count += 1;
        if c != n {
            counts.push(count);
            count = 0;
        }
    }
    count += 1;
    counts.push(count);
    let unhappy = max!(counts.len() - 2 * K, 1);
    println!("{}", S.len() - unhappy);
}


// // -*- coding:utf-8-unix -*-

// #[macro_use]
extern crate lazy_static;
extern crate num_bigint; // 0.2.2
extern crate num_traits; // 0.2.8
use num_bigint::BigInt;
use num_traits::Pow;
use petgraph::algo::dijkstra;
use petgraph::Directed;

// // use proconio::derive_readable;
use proconio::fastout;
use proconio::input;
// use std::convert::TryInto;
use ascii::{AsciiChar, AsciiString};
use itertools::concat;
use lazy_static::lazy_static;
// use libm::*;
use petgraph::Graph;
use std::cmp::*;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::*;
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use superslice::*;

// pub fn read<T: FromStr>() -> T {
//     let stdin = 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")
// }

// // lazy_static! {
// //     static ref H: Mutex<Vec<i32>> = Mutex::default();
// //     static ref W: Mutex<Vec<i32>> = Mutex::default();
// // }

// // let mut values = VALUES.lock().unwrap();
// // values.extend_from_slice(&[1, 2, 3, 4]);
// // assert_eq!(&*values, &[1, 2, 3, 4]);

use proconio::marker::Chars;
// use std::collections::HashMap;

// static ASCII_LOWER: [char; 26] = [
//     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
//     't', 'u', 'v', 'w', 'x', 'y', 'z',
// ];

// abc172-D
fn main() {
    input! {
        n: usize,
        k: usize,
        s: Chars
    }

    // let mut s_extend = Vec::new();
    // s_extend.push('R');
    // s_extend.extend_from_slice(s.as_slice());
    // s_extend.push('L');
    let mut changes_l2r = 0;
    let mut changes_r2l = 0;
    let mut old = None;
    let mut hap = 0;
    let mut del: i64 = 0;
    for s in s.iter() {
        if let Some(v) = old {
            if v != *s {
                if *s == 'L' {
                    changes_r2l += 1;
                } else {
                    changes_l2r += 1;
                }
            } else {
                hap += 1;
            }
        } else {
            if *s == 'L' {
                changes_r2l += 1;
                del -= 1;
            } else {
                // changes_l2r += 1;
            }
        }
        old = Some(*s);
    }

    if *s.last().unwrap() == 'R' {
        changes_r2l += 1;
        del -= 1;
    }

    let min_v = min(changes_r2l, changes_l2r);
    // eprintln!("{}, {}, {}", changes_r2l, changes_l2r, hap);
    if min_v <= k {
        // if min_v % 2 == 1 {
        //     println!("1:{}", min_v * 2 + hap - 1);
        //     return;
        // } else {
        if del == -2 && changes_r2l != changes_l2r {
            del = -1;
        }
        println!("{}", (min_v * 2 + hap) as i64 + del);
        return;
        // }
    }

    println!("{}", (hap + 2 * k) as i64);

    // println!("{}", ans);
}


import Foundation

func readWords<T>(_ f: (Substring) -> T) -> [T] {
    return readLine()!.split(separator: " ").map(f)
}

func main() {
    var nk = readWords { Int($0)! }.makeIterator()
    let n = nk.next()!
    let k = nk.next()!

    // 13 5
    // LRRLRLRRLRLLR
    // LRRLRLLLLRLLR
    // LRRLRRRRRRLLR
    // LRRLLLLLLLLLR
    // LRRRRRRRRRRRR (if LLRLLLLLLLL... then +1)

    let S = Array(readLine()!)
    var count = 0
    for i in 0..<n-1 {
        if S[i] == S[i+1] {
            count += 1
        }
    }

    print(min(count+k*2, n - 1))
}

main()


import Foundation

func readWords<T>(_ f: (Substring) -> T) -> [T] {
    return readLine()!.split(separator: " ").map(f)
}

func main() {
    var nk = readWords { Int($0)! }.makeIterator()
    let n = nk.next()!
    let k = nk.next()!

    // 13 3
    // LRRLRLRRLRLLR
    // LRRLRLLLLRLLR
    // LRRLRRRRRRLLR
    // LRRLLLLLLLLLR

    let S = ["R"] + Array(readLine()!) + ["L"]
    var count = 0
    var rl = 0
    for i in 0..<n-1 {
        if S[i] == S[i+1] {
            count += 1
        } else if S[i] == "R" && S[i+1] == "L" {
            rl += 1
        }
    }

    let change = rl > k ? k : rl

    print(count + change * 2)
}

main()


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8').trim()

const input = stdin.split('\n')

const [n, k] = input[0].split(' ').map(Number)
const s = input[1]

const sl = s.split('')

// 連続してる数-1
const ans = () => {
  let seq = 0
  let seqs = []

  for (let i = 1; i < n; i++) {
    if (sl[i] === sl[i - 1]) {
      seq++
    } else {
      seqs.push(seq)
      seq = 0
    }
  }
  seqs.push(seq)

  const hps = seqs.reduce((p, c) => p + c)

  console.log(Math.min(n - 1, hps + 2 * k))
}

ans()


import * as readline from 'readline';
const rl = readline.createInterface(process.stdin, process.stdout);

let line = 0;
let n: number;
let k: number;
let s: boolean[] = [];

rl.on("line", input => {
  line++;
  if (line === 1) {
    const ary = input.split(/\s+/).map(val=>parseInt(val));
    n = ary[0];
    k = ary[1];
  } else {
    const ss = input as string;
    s.length = ss.length;
    for (let i = 0; i < ss.length; i++) {
      s[i] = (ss.charAt(i) === 'L');
    }
    let x = _count(s) + k*2;
    if (x > n - 1) x = n - 1;
    console.log(x);
  }
});

function _count(s: boolean[]): number {
  let x = 0;
  for (let i = 0; i < s.length-1; i++) {
    if (s[i] === s[i+1]) x++;
  }
  return x;
}


import * as readline from 'readline';
const rl = readline.createInterface(process.stdin, process.stdout);

let line = 0;
let n: number;
let k: number;
let s: boolean[] = [];

rl.on("line", input => {
  line++;
  if (line === 1) {
    const ary = input.split(/\s+/).map(val=>parseInt(val));
    n = ary[0];
    k = ary[1];
  } else {
    const ss = input as string;
    s.length = ss.length;
    for (let i = 0; i < ss.length; i++) {
      s[i] = (ss.charAt(i) === 'L');
    }
    let x = _try(s, k, _count(s));
    console.log(x);
  }
});

function _try(s: boolean[], n: number, x: number): number {
  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      let s2 = _turn(s, i, j);
      const x2 = _count(s2);
      if (x2 > x) x = x2;
      if (n > 1) {
        x = _try(s2, n-1, x);
      }
    }
  }
  return x;
}

function _turn(s: boolean[], i: number, j: number): boolean[] {
  let r: boolean[] = [];
  r.length = s.length;
  for (let t = 0; t < s.length; t++) {
    r[t] = ((t >= i) && (t <= j)) ? !s[t] : s[t];
  }
  return r;
}

function _count(s: boolean[]): number {
  let x = 0;
  for (let i = 0; i < s.length-1; i++) {
    if (s[i] === s[i+1]) x++;
  }
  return x;
}


import * as fs from "fs"

// yarn compile template.ts で監視可能
// npx ts-node template.ts で実行可能

// ############################################################ //

// 配列の要素よりも大きかったら入れ替える
const chmax = <T>(ary: Array<T>, index: number, value: T): boolean => {
  if (ary[index] < value) {
    ary[index] = value
    return true
  }
  return false
}

// 配列の要素よりも小さかったら入れ替える
const chmin = <T>(ary: Array<T>, index: number, value: T): boolean => {
  if (ary[index] > value) {
    ary[index] = value
    return true
  }
  return false
}

// 2次元配列の行と列を入れ替える
const transpose = <T>(a: Array<Array<T>>) =>
  a[0].map((_, c) => a.map((r) => r[c]))

// 配列を作成して指定された値で初期化する
const createArray = <T>(length: number, initialValue: T): T[] => {
  const ary = []
  for (let i = 0; i < length; i++) {
    ary.push(initialValue)
  }
  return ary
}

// 配列の初期化などで使える、整数値の上限下限（これ同士を足してもオーバーフローしない）
const NUMBER_MAX = Math.floor(Number.MAX_SAFE_INTEGER / 2)
const NUMBER_MIN = Math.ceil(Number.MIN_SAFE_INTEGER / 2)

// ############################################################ //

type Renzoku = { char: string; length: number; index: number }

const renzokuLength = (s: string[]): Renzoku[] => {
  const res: Renzoku[] = []

  let nowChar = ""
  let nowIndex = 0
  let nowLength = 0

  for (let i = 0; i < s.length; i++) {
    if (nowChar !== s[i]) {
      if (i !== 0) {
        res.push({
          char: nowChar,
          index: nowIndex,
          length: nowLength
        })
      }
      nowChar = s[i]
      nowIndex = i
      nowLength = 1
    } else if (nowChar === s[i]) {
      nowLength++
    }
  }
  res.push({
    char: nowChar,
    index: nowIndex,
    length: nowLength
  })

  return res
}

const process = (n: number, k: number, s: string[]): string => {
  // L にそろえていく
  // R が連続しているところを見つける
  const renzoku = renzokuLength(s)
    .filter((e) => e.char === "R")
    .sort((a, b) => {
      if (a.index === 0) {
        return a.length - 1 + b.length
      } else if (b.index === 0) {
        return a.length + b.length - 1
      } else {
        return a.length + b.length
      }
    }) // 少ない順

  // 連続数が一番多いところから処理していく
  for (let i = 0; i < k; i++) {
    const now = renzoku.pop()
    if (!now) {
      if (s[0] === "R") {
        for (let j = 0; s[j] === "R"; j++) {
          s[j] = "L"
        }
      }
      break
    }
    for (let j = now.index; j < now.index + now.length; j++) {
      s[j] = "L"
    }
  }

  // 幸福度判定
  let kouhuku = 0
  for (let i = 1; i < s.length; i++) {
    if (s[i] === s[i - 1]) {
      if (i === s.length - 1 && s[i] === "R") {
        continue
      }
      kouhuku++
    }
  }

  return "" + kouhuku
}

const Main = (input: string): string => {
  const aa: string[][] = input.split("\n").map((e) => e.split(" "))
  const na0: number[] = aa[0].map((e) => parseInt(e))
  const [a, b] = na0

  const res = process(a, b, aa[1][0].split("")) + ""
  console.log(res)
  return res
}
 Main(fs.readFileSync("/dev/stdin", "utf8"))


a,b,c=map(int,input().split())
print(max(a-b,b-c,c-a,a-c,b-a,c-b))


*a,=map(int,input().split())
print(max(a)-min(a))


A = [int(t) for t in input().split()]

print(max(A) - min(A))


import numpy as np
N_List = np.array([map(int,input().split())])
N_List_a = np.sort(N_List)
print(sum(N_List_a[1:]-N_List[:-1]))


N_List = sorted(list(map(int,input().split())))
print(sum(N_List[1:]-N_List[:-1]))


a = [int(x) for x in input().split()]
a1 = abs(a[1] - a[0]) + abs(a[1] - a[2])
a2 = abs(a[2] - a[0]) + abs(a[2] - a[1])
print(min(a1,a2))


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class Main {

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int[] a = new int[3];
		sc.fill(a);

		int min = Integer.MAX_VALUE;
		for (int i = 0; i < 3; i++) {
			for (int j = 0; j < 3; j++) {
				if (i == j) {
					continue;
				}
				for (int k = 0; k < 3; k++) {
					if (i == k || j == k) {
						continue;
					}

					debug(a[i], a[j], a[k], Math.abs(a[i] - a[j]) + Math.abs(a[j] - a[k]));

					min = Math.min(min, Math.abs(a[i] - a[j]) + Math.abs(a[j] - a[k]));
				}
			}
		}

		System.out.println(min);
	}

	private static boolean isDebug = System.getProperty("sun.desktop") != null;

	private static void debug(Object... o) {
		if (isDebug) {
			System.err.println(Arrays.deepToString(o));
		}
	}

	public static class Scanner {
		private BufferedInputStream inputStream;
		private StringBuilder buffer = new StringBuilder();

		public Scanner(InputStream in) {
			inputStream = new BufferedInputStream(in);
		}

		public int nextInt() throws IOException {
			int num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(int[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
			}
		}

		public void fill(int[] a, int[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
				b[i] = nextInt();
			}
		}

		public long nextLong() throws IOException {
			long num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(long[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
			}
		}

		public void fill(long[] a, long[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
				b[i] = nextLong();
			}
		}

		public long[] nextLong(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++) {
				array[i] = nextLong();
			}

			return array;
		}

		public String next() throws IOException {
			int read = skip();
			do {
				buffer.append((char) read);
			} while ((read = inputStream.read()) > 0x20);

			String text = buffer.toString();
			buffer.delete(0, buffer.length());

			return text;
		}

		private int skip() throws IOException {
			int read;
			while ((read = inputStream.read()) <= 0x20)
				;

			return read;
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO 自動生成されたメソッド・スタブ

		int task1,task2,task3;
		int cost[] = new int[6];
		int ans=1000;

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str[] = br.readLine().split(" ");
		task1 = Integer.parseInt(str[0]);
		task2 = Integer.parseInt(str[1]);
		task3 = Integer.parseInt(str[2]);

		//1-2-3
		cost[0] = Math.abs(task1-task2)+Math.abs(task2-task3);
		//1-3-2
		cost[1] = Math.abs(task1-task3)+Math.abs(task3-task2);
		//2-1-3
		cost[2] = Math.abs(task2-task1)+Math.abs(task1-task3);
		//2-3-1
		cost[3] = Math.abs(task2-task3)+Math.abs(task3-task1);
		//3-1-2
		cost[4] = Math.abs(task3-task1)+Math.abs(task1-task2);
		//3-2-1
		cost[5] = Math.abs(task3-task2)+Math.abs(task2-task1);

		for(int i=0;i<6;i++) {
			if(ans > cost[i]) {
				ans = cost[i];
			}
		}

		System.out.println(ans);

	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

public class Main {

    int[] a;

    private void solve() {

        int min = (int)1e9 + 7;
        int max = 0;
        a = new int[3];
        for(int i = 0;i < 3;i++) {
            a[i] = nextInt();

            min = Math.min(min, a[i]);
            max = Math.max(max, a[i]);
        }

        out.println(max - min);
    }

    public static void main(String[] args) {
        out.flush();
        new Main().solve();
        out.close();
    }

    /* Input */
    private static final InputStream in = System.in;
    private static final PrintWriter out = new PrintWriter(System.out);
    private final byte[] buffer = new byte[4096];
    private int p = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (p < buflen)
            return true;
        p = 0;
        try {
            buflen = in.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (buflen <= 0)
            return false;
        return true;
    }

    public boolean hasNext() {
        while (hasNextByte() && !isPrint(buffer[p])) {
            p++;
        }
        return hasNextByte();
    }

    private boolean isPrint(int ch) {
        if (ch >= '!' && ch <= '~')
            return true;
        return false;
    }

    private int nextByte() {
        if (!hasNextByte())
            return -1;
        return buffer[p++];
    }

    public String next() {
        if (!hasNext())
            throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = -1;
        while (isPrint((b = nextByte()))) {
            sb.appendCodePoint(b);
        }
        return sb.toString();
    }

    public int nextInt() {
        return Integer.parseInt(next());
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public double nextDouble() {
        return Double.parseDouble(next());
    }
}


mport java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int a1 = sc.nextInt();
		int a2 = sc.nextInt();
		int a3 = sc.nextInt();
		sc.close();

		int min = Math.min(Math.min(a1, a2), a3);
		int max = Math.max(Math.max(a1, a2), a3);
		System.out.println(max - min);
	}
}


import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.math.*;
public class Main
{
    static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
   public static void main(String args[])
    {
        FastReader sc=new FastReader();
        PrintWriter pw=new PrintWriter(System.out);
        int t=1;//sc.nextInt();
        while(t-->0)
        {
           String s=sc.next(),st=sc.next();int f=0;
           for(int i=s.length();i>=0;i--)
           {
             String str=s.substring(i,s.length())+s.substring(0,i);
             if(str.equals(st)){pw.println("Yes");f=1;break;}
           }
           if(f==0) pw.println("No");
        }
           pw.close();
    }
}


import java.util.Scanner;

public class Main {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int min = 101;
    int max = 0;

    for (int i = 0; i < 2; i++) {
      int a = sc.nextInt();
      min = Math.min(a, min);
      max = Math.max(a, max);
    }

    System.out.println(max - min);

  }
}


#include<stdio.h>
int main()
{
	int i,j,a,b,c,t=0;
	scanf("%d%d%d",&a,&b,&c);
	if(a>b){t=b;b=a;a=t;}
	if(a>c){t=c;c=a;a=t;}
	if(b>c){t=c;c=b;b=a;}
	printf("%d\n",c-a);
	return 0;
}


#include<stdio.h>
int main()
{
	int s[105];
	for(int i=0;i<3;i++)
	{
		scanf("%d",&s[i]);
	}
	for(int i=0;i<3;i++)
	{
		for(int j=2;j>i;j--)
		{
			if(s[j]>s[j-1]){

			int t;
			t=s[j];
			s[j]=s[j-1];
			s[j-1]=t;

		  }
		}
	}
	printf("%d",s[0]-s[2]);
}


#include <stdio.h>

int main(void) {
  int a, b, c, max, copy;

  scanf("%d %d %d", &a, &b, &c);
  max = a;
  if (max < b) {
    max = b;
  }else {
    copy = a;
    a = b;
    b = copy;
  }
  if (max < c) {
    max = c;
  }else {
    copy = b;
    b = c;
    c = copy;
  }
  if (a > b) {
    copy = a;
    a = b;
    b = copy;
  }

  printf("%d\n", c - a);

  return 0;
}


#include "bits/stdc++.h"
#define DEBUG(x) cout<<#x<<": "<<x<<endl;
#define DEBUG_VEC(v) cout<<#v<<":";for(int i=0;i<v.size();i++) cout<<" "<<v[i]; cout<<endl
using namespace std;
#define vi vector<int>
#define vl vector<ll>
#define vii vector< vector<int> >
#define vll vector< vector<ll> >
#define vs vector<string>
#define pii pair<int,int>
#define pis pair<int,string>
#define psi pair<string,int>
#define pll pair<ll,ll>
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define MOD 1000000007
#define mod 1000000009
#define pi 3.14159265358979323846
#define Sp(p) cout<<setprecision(15)<< fixed<<p<<endl;
#define pb push_back
template<class T> void print(const T& x){cout << x << endl;}
int dx[4] = { 1,0,-1,0 }, dy[4] = { 0,1,0,-1 };
int dx2[8] = { 1,1,0,-1,-1,-1,0,1 }, dy2[8] = { 0,1,1,1,0,-1,-1,-1 };
typedef long long ll;
const int inf = 1000000001;
const ll INF = 1e18 * 4;

int main(){
    vi a;
    rep(i, 0, 3){
        int j; cin >> j;
        a.pb(j);
    }
    sort(a.begin(), a.end());
    int ans = min(a[1] - a[0], a[2] - a[1]);
    cout << ans << endl;

    return 0;
}


#include<bits/stdc++>
using namespace std;
int main(){
  vector<int> a(3);
  cin>>a[0]>>a[1]>>a[2];
  sort(a.begin(),a.end());
  cout<<a[2]-a[0]<<endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int a,b,c,z;
	cin>>a>>b>>c;
	z=(a-a)+abs(a-c)+abs(b-c);
	cout<<z<<endl;
	return 0;
}


#include<stdio.h>

int main()
{
    int a[3];
    int low=101,total_cost=0,s1=0,s2=0;
    for (int i=0;i<3;i++)
    {
        scanf("%d",&a[i]);
        if (a[i]<low){
            low=a[i];
            s1=i;
        }
    }
    a[s1]=101;
    int low2=101;
    for (int i=0;i<3;i++)
    {
        if (a[i]<low2){
            low2=a[i];
            s2=i;
        }
    }
    total_cost=low2-low;
    for (int i=0;i<3;i++)
    {
        if (i!=s1 && i!=s2)
            total_cost=total_cost+(a[i]-low2);
    }
    printf("%d",total_cost);

    return 0;
}


#include <stdio.h>

int main(void){
    int a1,a2,a3,cost=0,max=0,sec=0,trd=0;
    scanf("%d",&a1);
    max=a1;
    sec=a1;
    trd=a1;
    scanf("%d",&a2);
    if(a2>max){
      max=a2;
    }else{
      sec=a2;
    }
    scanf("%d",&a3);
    if(a3>max){
      trd=sec;
      sec=max;
      max=a3;
    }else if(a3>sec){
      trd=sec;
      sec=a3;
    }else{
      trd=a3;
    }
    cost+=max-sec;
    cost+=sec-trd;
    printf("%d\n",cost);
    return (0);
}


#include <stdio.h>
int main(void){
    // Your code here!
    int i, j, tmp,a;
    int number[3];

    for (i=0; i<3; ++i){
        scanf("%d", &number[i]);
    }

    for (i=0; i<3; ++i) {
        for (j=i+1; j<3; ++j) {
            if (number[i] > number[j]) {
                tmp =  number[i];
                number[i] = number[j];
                number[j] = tmp;
            }
        }
    }

    a = abs(number[0]-number[1]) + abs(number[1]-number[2]);

    printf("%d",a);

    return 0;
}


#include<stdio.h>

int main(void){
  int number[2];
  scanf("%d %d %d",&number[0],&number[1],&number[2]);
  int tmp;
  for (int i=0; i<3; ++i) {
    for (int j=i+1; j<3; ++j) {
      if (number[i] > number[j]) {
        tmp =  number[i];
        number[i] = number[j];
        number[j] = tmp;
      }
    }
  }

  printf("%d\n",number[2]-number[0]);
  return 0;
}


#include<stdio.h>

int main(void){
  int number[2];
  scanf("%d %d %d",&number[0],&number[1],&number[2]);

  for (i=0; i<3; ++i) {
    for (j=i+1; j<3; ++j) {
      if (number[i] > number[j]) {
        tmp =  number[i];
        number[i] = number[j];
        number[j] = tmp;
      }
    }
  }

  printf("%d\n",number[2]-number[0]);
  return 0;
}


#include <stdio.h>
int main(void)
{
    int N;
    scanf("%d", &N);

    int numbers[N];
    for(int i=0; i<N; i++){
        scanf("%d", &numbers[i]);
    }

    // 入力した値の最小公倍数を求めるプログラムを作成
    int count = 1;
    int amari[N];
    int sum_amari;
    int saisyou_koubaisuu;
    while(1){
        sum_amari = 0;
        for(int i=0; i<N; i++){
            //amari[i] = count%numbers[i];
            //sum_amari += amari[i];
            sum_amari += count%numbers[i]
        }
        if(sum_amari == 0){
            saisyou_koubaisuu = count;
            break;
        }
        count++;
    }
    // printf("saisyou_koubaisuu = %d\n", saisyou_koubaisuu);

    int f;
    int ans = -1;
    for(int i=0; i<saisyou_koubaisuu; i++){
        f = 0;
        for(int j=0; j<N; j++){
            f += i%numbers[j];
        }
        if(ans < f){
            ans = f;
        }
        // printf("%d %d\n", i, f);
    }

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

    return 0;
}


function main(input) {
  const a1 = parseInt(input.split(" ")[0], 10);
  const a2 = parseInt(input.split(" ")[1], 10);
  const a3 = parseInt(input.split(" ")[2], 10);
  var arr=[a1,a2,a3]
  var max=Math.max.apply(null,arr );
  var min=Math.min.apply(null, arr);
  console.log(max-min);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict"

function main(input) {
    let nums = input.split(' ')
    nums = nums.map(x => +x)
    nums.sort()//.reverse()
    let num = 0;
    for (let i=0; i<nums.length;i++) {
        let red = (i >= 1) ? nums[i - 1] : 0
        num += Math.abs(nums[i] - red)
    }
    num -= nums[0]
    console.log(num)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


var input=require("fs").readFileSync(0,"utf8");
var a=input.match(/\d+/g).map(Number);
var x=Math.abs(a[0]-a[1]),
	y=Math.abs(a[1]-a[2]),
	z=Math.abs(a[2]-a[0]);
var ans=x+y+z-Math.max(x,y,z);
console.log(ans);


const main = (arg) => {
  const lines = arg.trim().split('\n');
  const A = lines[0].split(' ').map((x) => Number.parseInt(x));
  A.sort((a, b) => b - a);
  console.log(A[2] - A[0]);
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (arg) => {
  const lines = arg.trim().split('\n');
  console.log(lines[0]);
  const A = lines[0].split(' ').map((x) => Number.parseInt(x));
  A.sort((a, b) => b - a);
  console.log(A[2] - A[0]);
};
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


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', () => {
    const arr = lines[0].split(' ');
    const max = Math.max(...arr);
    const min = Math.min(...arr);

    let result = Math.abs(max - min);
    console.log(result);
});


package main

import (
    . "fmt"
    "sort"
)

func main() {
    var a1, a2, a3 int
    Scanf("%d %d %d", &a1, &a2, &a3)

    var arr []int = []int{a1, a2, a3}

    sort.Sort(sort.IntSlice(arr))

    sum := 0
    for i := 1; i < 3; i++ {
        sum += arr[i] - arr[i - 1]
    }

    Println(sum)
}


package main

import (
  "fmt"
  "sort"
)

func main() {
  a := make([]int, 3)
  for i := 0; i < 3; i++ {
    fmt.Scan(&a[i])
  }
  sort.Ints(a)
  fmt.Println(a[2] - a[0])
}


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	arr := strings.Split(sc.Text(), " ")
	nums := make([]int, 3)
	for i := range arr {
		nums[i], _ = strconv.Atoi(arr[i])
	}
	sort.Ints(nums)
	fmt.Println(nums[len(nums)-1] - nums[0])
}


package main

import (
	"fmt"
	"sort"
)

func abs(a int) int {
	if a > 0 {
		return a
	}
	return a
}

func main() {
	var a [3]int
	fmt.Scan(&a[0], &a[1], &a[2])
	b := a[:]
	sort.Ints(b)

	fmt.Println(abs(b[0]-b[1]) + abs(b[1]-b[2]))
}


package main

import (
	"fmt"
)

func abs(a int) int {
	if a > 0 {
		return a
	}
	return a
}

func main() {
	var a, b, c int
	fmt.Scan(&a, &b, &c)

	fmt.Println(abs(a-b) + abs(b-c))
}


package main

import (
	"fmt"
)

func abs(a int) int {
	if a > 0 {
		return a
	}
	return b
}

func main() {
	var a, b, c int
	fmt.Scan(&a, &b, &c)

	fmt.Println(abs(a-b) + abs(b-c))
}


a=gets.split.map(&:to_i).sort;p a[1] - a[0] + a[2] - a[1]


a = []
a[0], a[1], a[2] = gets.split.map(&:to_i)
a = a.sort

puts (a[1] - a[0]) + (a[2] - a[1])


a = gets.split.map(&:to_i)
a.sort!
sum = 0
sum += (a[1] - a[0]).abs
sum += (a[2] - a[1]).abs
puts sum


s=gets.chomp.chars
t=gets.chomp.chars
ans=0
for i in 0...s.size
  s << s[0]
  s.shift
  ans=1 if s==t
end
puts ans==0? "No":"Yes"


a, b, c = gets.chomp.split.map(&:to_i)

array = [a - b, b - c, c - a]

puts array.min.abs


# 3 個のタスクがあり、あなたは全てのタスクを完了させなければなりません。
# はじめ、任意の 1 個のタスクをコスト 0 で完了できます。
# また、i 番目のタスクを完了した直後にコスト |Aj−Ai| で j 番目のタスクを完了できます。
# ここで |x| は x の絶対値を表します。
# 全てのタスクを完了するのに要する合計コストの最小値を求めてください。

a = gets.chomp.split
a.length.times do |i|
    a[i] = a[i].to_i
end

costs = []
ai_permu_array = a.permutation(a.length).to_a

a.length.times do |i|
    ai_permu_array.each do |ai_permu|
        cost = 0
        next_cost = 0
        ai_permu.length.times do |k|
            if k == i
                cost += next_cost
                next_cost = ai_permu[k]
            else
                cost += (ai_permu[k] - next_cost).abs
                next_cost = ai_permu[k]
            end
        end
        costs << cost
    end
end

puts costs.min


#[allow(unused_macros, dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

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

#[allow(unused_macros, dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

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

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

#[allow(dead_code)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    size: Vec<usize>,
}

#[allow(dead_code)]
impl UnionFind {
    fn new(n: usize) -> UnionFind {
        let mut p = vec![0; n];
        for i in 0..n {
            p[i] = i;
        }
        return UnionFind {
            parent: p,
            rank: vec![0; n],
            size: vec![1; n],
        };
    }

    fn find(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let p = self.parent[x];
            let pr = self.find(p);
            self.parent[x] = pr;
            pr
        }
    }

    fn same(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    fn unite(&mut self, a: usize, b: usize) {
        let a_root = self.find(a);
        let b_root = self.find(b);
        if a_root == b_root {
            return;
        }
        if self.rank[a_root] > self.rank[b_root] {
            self.parent[b_root] = a_root;
            self.size[a_root] += self.size[b_root];
        } else {
            self.parent[a_root] = b_root;
            self.size[b_root] += self.size[a_root];
            if self.rank[a_root] == self.rank[b_root] {
                self.rank[b_root] += 1;
            }
        }
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root]
    }
}

const MOD_P: usize = 1000000007;

#[allow(dead_code)]
// fact(n) = n! mod p
fn fact(n: usize) -> usize {
    let mut acc = 1;
    for i in 1..n + 1 {
        acc = acc * i % MOD_P;
    }
    acc
}

#[allow(dead_code)]
fn mod_pow(b: usize, mut e: usize) -> usize {
    let mut base = b;
    let mut acc = 1;

    while e > 1 {
        if e % 2 == 1 {
            acc = acc * base % MOD_P;
        }
        e /= 2;
        base = base * base % MOD_P;
    }

    if e == 1 {
        acc = acc * base % MOD_P;
    }

    acc
}

#[allow(dead_code)]
fn comb(n: usize, r: usize) -> usize {
    // nCr = n! / (r! (n-r)!) = n! (r!)^(p-2) ((n-r)!)^(p-2)
    let x = ((n - r + 1)..(n + 1)).fold(1, |p, x| p * x % MOD_P);
    let y = mod_pow(fact(r), MOD_P - 2);
    x * y % MOD_P
}

#[allow(dead_code)]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if a % b == 0 {
        b
    } else {
        gcd(b, a % b)
    }
}

#[allow(dead_code)]
fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

use std::cmp::{max, min};

fn main() {
    input! {
        mut a: [usize;3],
    }
    a.sort();
    let ans = min(a[1] - a[0] + a[2] - a[1], a[2] - a[1] + a[1] - a[0]);
    println!("{}", ans);
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let  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 $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };

    ($iter:expr, mut $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")
    };
}

fn main() {
    input! {
        a: [i32; 3]
    }
    let mut b = vec![
        (a[0] - a[1]).abs(),
        (a[1] - a[2]).abs(),
        (a[2] - a[0]).abs(),
    ];
    b.sort();
    println!("{}", b[0] + b[1]);
}


use std::io;

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 mut v:Vec<i32> = procon_read();
	v.sort();
	println!("{}", (v[1] - v[0]) + (v[2] - v[1]));
}


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

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

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

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

#[allow(unused_macros)]
macro_rules! max {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      max($x,max!($($xs)+))
    };
  }

#[allow(unused_macros)]
macro_rules! min {
    ($x:expr) => {
      $x
    };
    ($x:expr, $($xs:tt)+) => {
      min($x,min!($($xs)+))
    };
  }

use std::ascii::AsciiExt;
use std::cmp;
use std::collections::VecDeque;
use std::io::Write;
use std::iter::Iterator;

fn main() {
    input! {
        n:usize,
        m:usize,
        bredge:[(usize, usize);m],
    }

    let mut bredge_mut = bredge;
    bredge_mut.sort_by_key(|a| a.1);

    let mut ans = 1;
    let mut t = bredge_mut[0].1;
    for i in 0..m {
        if  t <= bredge_mut[i].0 {
            ans += 1;
            t = bredge_mut[i].1;
        }
    }

    println!("{}", ans);

}


fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();
    let a: u16 = read(&mut stdin_lock, &mut buf, b' ');
    let b: u16 = read(&mut stdin_lock, &mut buf, b' ');
    let c: u16 = read(&mut stdin_lock, &mut buf, b'\n');
    let mut vs: Vec<u16> = vec![a, b, c];
    vs.sort_unstable();
    let ans = vs[2] - vs[0];
    println!("{}", ans);
}


let i=readLine()!.characters.split(" ").map{Int(String($0))!}.sort();print(i[2]-i[0])


import Foundation
var strA=readLine()!.componentsSeparatedByString(" ")
var A=[Int]()
for i in strA{
  A.append(Int(i)!)
}
let max=A.maxElement()
let min=A.minElement()
print(max!-min!)


import Foundation

let arguments = ProcessInfo.processInfo.arguments
let inputs = arguments.compactMap(Int.init)

let output = inputs.sorted(>).reduce(0) { $0-$1 }
print(output)


import Foundation
let S=readLine()!
let T=readLine()!
var a=0
for_i:for i 0..<S.characters.count{
  a=0
  if S[0]==T[i] {
    for_j:for j 1..<S.characters.count{
      if S[j]==T[(i+j)%5]{
        a=a+1
      }else {
        break for_j
      }
    }
  }
  if a==S.characters.count{
    print("Yes")
    break for_i
  }
}
if a!=S.characters.count{
  print("No")
}


declare var require: (x: string) => any;

function Main(input: string[]) {
  const ab = input[0].split(' ').map(x => +x);
  console.log(Math.max(...ab) - Math.min(...ab));
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));


//declare var require: (x: string) => any;

function Main(input: string[]) {
  const ab = input[0].split(' ').map(x => +x);
  console.log(Math.max(...ab) - Math.min(...ab));
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const a = stdin
  .split('\n')[0]
  .split(' ')
  .map(Number)

a.sort((a, b) => b - a)

let cost = 0

cost = Math.abs(a[0] - a[1])

cost += Math.abs(a[1] - a[2])

console.log(cost)


"use strict"
let fs = require('fs');
let input = fs.readFileSync("/dev/stdin", "utf8").split(/\s/);
const inp = input.map(x => +x);
console.log(Math.max.apply(null, inp) - Math.min.apply(null, inp));


declare var require: (x: string) => any;

function Main(input: string[]) {
    const ab = input[0].split(' ').map(x => +x);
    console.log((Math.max(...ab) - Math.min(...ab)))
}

Main(require('fs').readFlieSync('dev/stdin', 'utf8').split("\n"));


declare var require: (x: string) => any;

function Main(input: string[]) {
  const ab: number[] = input[0].split(' ').map(x => +x);
  console.log(Math.max(ab) - Math.min(ab));
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8').split('\n'));


def solve(N,K,A):
    for i in range(K):
        arr = [0] * (N + 1)

        for ind,j in enumerate(A):
            arr[max(ind-j,0)] += 1
            arr[min(ind+j+1, N)] -= 1

        A[0] = arr[0]
        for k in range(N-1):
            A[k+1] = A[k] + arr[k+1]

        if arr[0] ==N and arr[-1] == -N:
            return A
    return A

if __name__ == "__main__":
    n,k = map(int, input().split())
    a = list(map(int, input().split()))
    ans = solve(n,k,a)
    print(*ans)


def solve():
    N,K = map(int, input().split())
    A = list(map(int, input().split()))

    for i in range(K):

        arr = [0] * (N + 1)

        for ind,j in enumerate(A):
            arr[max(ind-j,0)] += 1
            arr[min(ind+j+1, N)] -= 1

        A[0] = arr[0]
        for k in range(N-1):
            A[k+1] = A[k] + arr[k+1]

        if arr[0] ==N and arr[-1] == -N:
            return A
    return A

if __name__ == "__main__":
    ans = solve()
    print(*ans)


N, K = map(int, input().split())
A = list(map(int, input().split()))

for i in range(K):
  new = [0] * (N+1)
  for j in range(N):
    new[max(0, j-A[j])] += 1
    if j+A[j]+1 <= N-1:
      new[j+A[j]+1] -= 1
  A[0] = new[0]
  for j in range(1, N):
    new[j] += new[j-1]
    A[j] = new[j]
  for ai in A:
    if ai != N:
      break
  else:
    break

print(' '.join([str(ai) for ai in A]))


import sys
import numpy as np
from numba import njit

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

@njit('i8[:](i8,i8,i8[:])', cache=True)
def func(n, k, A):
    for _ in range(k):
        B = np.zeros(n + 1, np.int64)
        for i, a in enumerate(A):
            B[max(0, i - a)] += 1
            B[min(i + a + 1, n)] -= 1
        A = B.cumsum()[:-1]
    return A

def main():
    N, K = map(int, readline().split())
    A = np.array(readline().split(), np.int64)
    ans = func(N, K, A)
    print(*ans)

if __name__ == '__main__':
    main()


import sys
import numpy as np

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N, K = map(int, readline().split())
    np.set_printoptions(precision=0)
    A = np.array(readline().split(), np.int64)
    for _ in range(K):
        B = np.zeros(N + 1)
        for i, a in enumerate(A):
            B[max(0, int(i - a))] += 1
            B[min(int(i + a + 1), N)] -= 1
        A = B.cumsum()[:-1]
    print(*A)

if __name__ == '__main__':
    main()


import sys
import numpy as np

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N, K = map(int, readline().split())
    np.set_printoptions(precision=0)
    A = np.array(readline().split(), np.int64)
    for _ in range(K):
        B = np.zeros(N + 1)
        for i, a in enumerate(A):
            B[max(0, int(i - a))] += 1
            B[min(int(i + a + 1), N)] -= 1
        B = B.cumsum()
        A = np.copy(B[:N])
    print(' '.join(map(str, list(map(int, A)))))

if __name__ == '__main__':
    main()