function Main(input) {
  const row = input.split(" ");
    	let X = parseInt(row[0], 10);
    	let K = parseInt(row[1], 10);
    	const D = parseInt(row[2], 10);
    let absX = Math.abs(X);
    let a = absX / D;
    let ans;
    if(X == D && K % 2 === 0){
      ans = X;

    } else {
    if((absX /D) >= K) {
       ans = absX - D * K;

    } else {
       K2 = K - a;
       absX = absX - K2 * D;
       if(K2 % 2 === 1) {
    　ans = absX - D;
      } else {
         ans = absX;
      }
    }
    } console.log(Math.abs(ans));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


package main

import (
	"fmt"
)

func main() {

	var x, k, d int64
	fmt.Scan(&x, &k, &d)
	if x < 0 {
		x = -x
	}
	n := x / d

	t1 := x % d
	t2 := t1 -d

	var ans int64

	if k <= n {
		ans = x - k * d
	} else {
		if (k-n) % 2 == 0 {
			ans = t1
		} else {
			ans = -t2
		}
	}
	fmt.Println(ans)
}


package main

import (
	"fmt"
)

func main(){
	var x, k, d int
	fmt.Scan(&x, &k, &d)

	if x == 0 {
		if k % 2 == 0 {
			fmt.Println(0)
			return
		}
		fmt.Println(d)
		return
	}
	x = abs(x)
	ans := x % d
	a := x / d
	if a > k {
		// 往復に辿り着く前に終る
		fmt.Println(x - k * d)
		return
	} else if a <= k  {
		// 往復する
		if (k - a) % 2 == 0 {
			fmt.Println(ans)
			return
		} else if (k-a) % 2 == 1 {
			if ans > 0 {
				ans -= d
			} else {
				ans += d
			}
			fmt.Println(abs(ans))
			return
		}
	}
}

func abs(n int) int {
	y := n >> 63
	return (n ^ y) - y
}


package main

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
)

func init() {
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
}

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

func readInt64() int64 {
	n, _ := strconv.ParseInt(ReadString(), 10, 64)
	return n
}

func readInt() int {
	return int(readInt64())
}

// 10 11 12 => [10, 11, 12]
func readIntSlice(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; i++ {
		a[i] = readInt()
	}
	return a
}

func get2byte(size int) [][]byte {
	a := make([][]byte, size)
	for i := 0; i < size; i++ {
		var low string
		fmt.Scan(&low)
		a[i] = []byte(low)
	}
	return a
}

func transpose(a [][]int) {
	n := len(a)
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			a[i][j], a[j][i] = a[j][i], a[i][j]
		}
	}
}

func fact(n, m int) int {
	res := 1
	for i := m + 1; i <= n; i++ {
		res *= i
	}
	return res
}

func perm(n, r int) int {
	if r > n {
		return 0
	}
	return fact(n, n-r)
}

func comb(n, m int) int {
	if m > n {
		return 0
	}
	return fact(n, n-m) / fact(m, 0)
}

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

func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

func min64(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

func main() {
	x, k, d := readInt64(), readInt64(), readInt64()
	fmt.Println(solve(x, k, d))
}

func solve(x, k, d int64) int64 {
	np := (k - x/d) / 2
	nm := (k + x/d) / 2
	if np < 0 {
		return int64(math.Abs(float64(x - k*d)))
	} else if nm < 0 {
		return int64(math.Abs(float64(x + k*d)))
	}
	var res []int64
	for i := -1; i <= 1; i++ {
		xp := np + int64(i)
		if xp < 0 {
			continue
		}
		xm := k - xp

		if xm < 0 {
			continue
		}
		res = append(res, int64(math.Abs(float64(x+(xp-xm)*d))))
	}
	for i := -1; i <= 1; i++ {
		xm := nm + int64(i)
		if xm < 0 {
			continue
		}
		xp := k - xm
		if xp < 0 {
			continue
		}
		res = append(res, int64(math.Abs(float64(x+(xp-xm)*d))))
	}
	return min64(res...)
}


package main

import ("fmt")

func main() {

  var(
    X,K,D,i int
  )
  fmt.Scan(&X,&K,&D)
  if D<0{
    var d = -D
  }else{var d=D}

  for i:=0; i < K;i++{

    if X >= 0{X = X - d}else{X = X + d}

  }
  if X<0 {var x=-X}else{var x=X}
    print(x)
}


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

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

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

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

func nextInt3() (int64, int64, int64) {
	return nextInt(), nextInt(), nextInt()
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

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

	x, k, d := nextInt3()
	x = abs(x)

	var ans int64
	if x >= d*k {
		ans = x - d*k
		puts(ans)
		return
	}

	y := x / d
	k -= y
	x -= y * d
	if k%2 == 0 {
		ans = x
	} else {
		ans = d - x
	}
	puts(ans)
}


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

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

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

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

func nextInt3() (int, int, int) {
	return nextInt(), nextInt(), nextInt()
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

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

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

	x, k, d := nextInt3()
	x = abs(x)

	var ans int
	if x >= d*k {
		ans = x - d*k
		puts(ans)
		return
	}

	y := x / d
	k -= y
	x -= y * d
	if k%2 == 0 {
		ans = x
	} else {
		ans = d - x
	}
	puts(ans)
}


x, k, d = gets.split(" ").map &:to_i
if (k*d) <= x.abs
  puts x.abs - k*d
  exit
end
l = x.abs/d
if (k - l)%2 == 1
  puts (x.abs - l*d -d).abs
else
  puts x.abs - l*d
end


x,k,d = gets.chomp.split.map(&:to_i)
abso = x.abs
min = abso/d
if min >= k
  puts abso - k*d
elsif (k - min).odd?
  puts (abso - (min + 1)*d).abs
else
  puts abso%d
end


x, k, d = gets.split(" ").map(&:to_i)
if x.abs >= k * d
  puts x.abs - (k * d)
  exit
end
xx=0
yy=1
flag=false
before_0 = x / d
if (k - before_0) % 2 == 0
  puts (x - (before_0 * d)).abs
  flag=true
  yy+=1
else (k - before_0) % 2 != 0
  puts  (x - (before_0 * d) - d).abs
  flag=false
  xx+=1
end


x, k, d = gets.split(" ").map &:to_i
if (k*d) <= x.abs
  puts x.abs - k*d
  exit
end
l = x.abs/d
if (k - l)%2 == 1
  puts (x.abs - (k-l)*d -d).abs
else
  puts x.abs - (k-l)*d
end


x,k,d = gets.chomp.split(' ').map(&:to_i)
all = [[x]]
# p all[0]
# p all[0][0]
min = x
i = 0
while i < k
  a = []
  j = 0
  while j < all[i].size
    a << (all[i][j]+d) if (all[i][j]+d).abs < min
    a << (all[i][j]-d) if (all[i][j]-d).abs < min
    min = all[i][j]+d if (all[i][j]+d).abs < min
    min = all[i][j]-d if (all[i][j]-d).abs < min
    # a << (all[i][j]+d)
    # a << (all[i][j]-d)
    j += 1
  end
  all << a
  i += 1
end
p min


x,k,d = gets.chomp.split(' ').map(&:to_i)
all = [[x]]
# p all[0]
# p all[0][0]
min = x
i = 0
while i < k
  a = []
  j = 0
  while j < all[i].size
    min = all[i][j]+d if (all[i][j]+d).abs < min
    min = all[i][j]-d if (all[i][j]-d).abs < min
    a << (all[i][j]+d)
    a << (all[i][j]-d)
    j += 1
  end
  all << a
  i += 1
end

p min


fn input_line() -> Vec<String> {
  let mut buf = String::new();
  std::io::stdin().read_line(&mut buf).unwrap();
  return buf
    .split_whitespace()
    .map(|word| String::from(word))
    .collect();
}

fn main() {
  let inputs = input_line();
  let x: i64 = inputs[0].parse().unwrap();
  let k: i64 = inputs[1].parse().unwrap();
  let d: i64 = inputs[2].parse().unwrap();

  let plus_x = if x < 0 {
    -x
  } else {
    x
  };

  let x_per_d = plus_x / d;

  let ans = if k <= x_per_d {
    plus_x - d * k
  } else {
    let x_mod_d = plus_x % d;

    if (k - x_per_d) % 2 == 0 {
      x_mod_d
    } else {
      -(x_mod_d - d)
    }
  };

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


fn main(){
 proconio::input!{mut x:i64,mut k:i64,d:i64};
 let mut x=x.abs();
 let s=k.min(x/d);
 k-=s;
 x-=s*d;
 let ans=if k%2==0{x}else{d-x};
 println!("{}",ans);
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($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 $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [graph1; $len:expr]) => {{
        let mut g = vec![vec![]; $len];
        let ab = read_value!($next, [(usize1, usize1)]);
        for (a, b) in ab {
            g[a].push(b);
            g[b].push(a);
        }
        g
    }};
    ($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:tt ]) => {{
        let len = read_value!($next, usize);
        read_value!($next, [$t; len])
    }};
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input! {
        x: i64, k: i64, d: i64,
    }
    let mut x = x.abs();
    if k % 2 == 1 {
        x = (x - d).abs()
    }
    let q = min(k / 2, x / (2 * d));
    let q1 = min(k / 2, x / (2 * d) + 1);
    puts!("{}\n", min((x - q * 2 * d).abs(), (x - q1 * 2 * d).abs()));
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


use proconio::{input, fastout};
use std::cmp::{min};

#[fastout]
fn main() {
    input! {
        x: isize,
        k: isize,
        d: isize
    }

    let a = k - min(x / d, k);
    let b = x - (min(x / d, k) * d);
    if a % 2 == 0 {
        println!("{}", b.abs());
    }else{
        println!("{}", (b - d).abs());
    }

}


use std::io::{stderr, stdin, stdout, BufReader, BufWriter, Cursor, Read, Write};
use std::iter::Iterator;
use std::str::FromStr;
use std::cmp::min;
// use std::slice::Iter;
// use std::vec::IntoIter;

#[allow(dead_code)]
fn main() {
  let stdin = stdin();
  let r = &mut BufReader::new(stdin.lock());
  let stdout = stdout();
  let w = &mut BufWriter::new(stdout.lock());
  let stderr = stderr();
  let err = &mut BufWriter::new(stderr.lock());
  run(r, w, err);
  w.flush().unwrap();
  err.flush().unwrap();
}

macro_rules! _ft { () => (impl FnOnce(&mut Cursor<Vec<u8>>, &mut Vec<u8>, &mut Vec<u8>)); }

#[allow(dead_code)]
fn test(input: &str, output: &str, f: _ft!()) {
  let r = &mut Cursor::new(input.as_bytes().to_vec());
  let w: &mut Vec<u8> = &mut Vec::new();
  let err: &mut Vec<u8> = &mut Vec::new();
  f(r, w, err);
  let mut stderr = stderr();
  writeln!(stderr, "{}", String::from_utf8(err.to_vec()).unwrap()).unwrap();
  stderr.flush().ok();
  assert_eq!(String::from_utf8(w.to_vec()).unwrap(), output)
}

#[allow(dead_code)]
macro_rules! t {
  ($f: ident => $input: expr, $output: expr) => (
    #[test]
    fn $f() { test($input, $output, run); }
  );
}

#[allow(unused_macros)]
macro_rules! args {
  ($($arg: expr),*) => ({
    let mut s = String::new();
    $(s += &format!("{} ", $arg);)*
    s.pop().unwrap();
    s
  });
}

#[allow(unused_macros)]
macro_rules! st {
  ($name: ident => $($p: ident : $t: ty),+) => (
    struct $name { $($p : $t),+ }
    impl FromStr for $name {
      type Err = ();
      fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut iter = s.split_whitespace();
        Ok(Self {
          $($p: iter.next().unwrap().parse::<$t>().unwrap(),)+
        })
      }
    }
  );
  ($name: ident => $($($p: ident),+: $t: ty);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($($p: ident),+: $($t: ty),+);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($p: ident),+: $t: ty) => (st!($name => $($p : $t),+););
  ($name: ident => $($p: ident),+: $($t: ty),+) => (st!($name => $($p : $t),+););
}

fn _read_iter<R: Read>(reader: &mut R) -> impl Iterator<Item=char> + '_ {
  reader.by_ref()
    .bytes()
    .map(|c| c.unwrap() as char)
    .skip_while(|c| c.is_whitespace())
}

#[allow(dead_code)]
fn read<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| !c.is_whitespace()).collect::<String>();
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read_line<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| c != &'\n').collect::<String>();
  let str = if str.ends_with('\r') { &str[0..str.len() - 1] } else { &str };
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read1<R: Read, T>(reader: &mut R, mut f: impl FnMut(char) -> T) -> T {
  f(_read_iter(reader).next().unwrap())
}

#[allow(dead_code)]
fn read1_line<R: Read, T>(reader: &mut R, f: impl FnMut(char) -> T) -> Vec<T> {
  _read_iter(reader).take_while(|c| c != &'\n').map(f).collect::<Vec<_>>()
}

/// 1要素読む
#[allow(unused_macros)]
macro_rules! r {
  ($stream: expr) => (read::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));

  ($stream: expr; $t: ty) => (read::<$t,  _>($stream));
  ($stream: expr; $($t: ty),+) => (($(r!($stream; $t)),*));

  ($stream: expr; $t: ty; 1~) => (read::<$t,  _>($stream) - 1);
  ($stream: expr; $($t: ty),+; 1~) => (($(r!($stream; $t) - 1),*));

  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| r!($stream; $t)).collect::<Vec<_>>());
  ($stream: expr; $t: ty; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

#[allow(unused_macros)]
macro_rules! r1 {
  ($stream: expr) => (read1($stream, |c| c));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $f: expr) => (read1($stream, $f));
  ($stream: expr; $f: expr; $n: expr) => ((0..$n).map(|_| r1!($stream, $f)).collect::<Vec<_>>());
  ($stream: expr; $f: expr; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r1!($stream; $f)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

/// 1行読む
#[allow(unused_macros)]
macro_rules! rl {
  ($stream: expr) => (read_line::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $t: ty) => (read_line::<$t,  _>($stream));
  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| rl!($stream; $t)).collect::<Vec<_>>());
}

macro_rules! _writes {
  ($stream: expr; $arg0: expr, $($arg: expr),*) => ({
    write!($stream, "{}", $arg0).ok();
    $(write!($stream, " {}", $arg).ok();)*
  });
}

/// write
#[allow(unused_macros)]
macro_rules! w {
  ($stream: expr) => (write!($stream, " ").ok());
  ($stream: expr; ) => (w!($stream));
  ($stream: expr, ) => (w!($stream));

  ($stream: expr; $arg: expr) => (write!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (w!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (_writes!($stream; $arg0, $($arg),+));
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (w!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (write!($stream, $($arg)*).ok());
}

/// write_line
#[allow(unused_macros)]
macro_rules! wl {
  ($stream: expr) => (writeln!($stream).ok());
  ($stream: expr, ) => (wl!($stream));
  ($stream: expr; ) => (wl!($stream));

  ($stream: expr; $arg: expr) => (writeln!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (wl!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => ({
    _writes!($stream; $arg0, $($arg),+);
    wl!($stream)
  });
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (wl!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (writeln!($stream, $($arg)*).ok());
}

/// write Vec
#[allow(unused_macros)]
macro_rules! w_vec {
  ($stream: expr; $vec: expr) => ({
    let mut iter = $vec.iter();
    match iter.next() { Some(&i) => { w!($stream, "{}", i); }, None => {}, }
    for &i in iter { w!($stream, " {}", i); }
  });
}

/// write_line Vec
#[allow(unused_macros)]
macro_rules! wl_vec {
  ($stream: expr; $vec: expr) => ({
    w_vec!($stream; $vec);
    wl!($stream)
  });
}

trait VecAlias<T> {
  fn select<U>(&self, f: impl FnMut(&T) -> U)  -> Vec<U>;
}

impl<T> VecAlias<T> for Vec<T> {
  fn select<U>(&self, mut f: impl FnMut(&T) -> U)  -> Vec<U> {
    self.iter().map(|i| f(i)).collect::<Vec<_>>()
  }
}

trait VecOrdAlias<T> {
  fn asc(&mut self);
  fn desc(&mut self);
}

impl<T: Ord> VecOrdAlias<T> for Vec<T> {
  fn asc(&mut self) { self.sort_unstable(); }
  fn desc(&mut self) { self.sort_unstable_by(|i, j| j.cmp(i)); }
}

#[allow(unused_macros)]
macro_rules! v {
  ($elem: expr; $n: expr) => (vec![$elem; $n as usize]);
  ($elem: expr; $h: expr, $w: expr) => (vec![vec![$elem; $w as usize]; $h as usize]);
}

#[allow(unused_macros)]
macro_rules! check_v {
  ($h: expr, $w: expr => $i: expr, $j: expr) => (
    $i >= 0 && $i < $h && $j >= 0 && $j < $w
  );
}

#[allow(unused_macros)]
macro_rules! check_get_v {
  ($($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if (check_v!($h, $w => $i, $j)) { Some(($($vec[$i as usize][$j as usize],)+)) }
    else { None }
  );
  (up; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i - 1, $j)
  );
  (down; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i + 1, $j)
  );
  (left; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i, $j - 1)
  );
  (right; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i, $j + 1)
  );
}

#[allow(unused_macros)]
macro_rules! get_v {
  ($($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    ($($vec[$i as usize][$j as usize], )+)
  );

  (up; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $i > 0 { Some(($($vec[($i - 1) as usize][$j as usize],)+)) } else { None }
  );
  (down; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $i < $h - 1 { Some(($($vec[($i + 1) as usize][$j as usize],)+)) } else { None }
  );
  (left; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $j > 0 { Some(($($vec[$i as usize][($j - 1)  as usize],)+)) } else { None }
  );
  (right; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $j < $w - 1 { Some(($($vec[$i as usize][($j + 1) as usize],)+)) } else { None }
  );
}

#[allow(dead_code)]
struct Point<T> { i: T, j: T }

#[allow(unused_macros)]
macro_rules! pos {
  ($i: expr, $j: expr) => (Point { i: $i, j: $j });
  (up; $i: expr, $j: expr) => (pos!($i - 1, $j));
  (down; $i: expr, $j: expr) => (pos!($i + 1, $j));
  (left; $i: expr, $j: expr) => (pos!($i, $j - 1));
  (right; $i: expr, $j: expr) => (pos!($i, $j + 1));
}

#[allow(unused_variables)]
fn run<R: Read, W: Write, E: Write>(reader: &mut R, writer: &mut W, err: &mut E) {
  let (x, k, d) = r!(reader; i64, i64, i64);
  let x = x.abs();
  if k == 1 { w!(writer; min(x, (x - d).abs())); return; }
  if x / k >= d { w!(writer; x - k * d); return; }
  let ans =
    if k % 2 == 0 {
      let a = x % (2 * d);
      if a > d { 2 * d - a } else { a }
    }
    else {
      let a = (x % (2 * d) - d);
      a.abs()
    };
  // let ans = if k % 2 == 0 { x } else { x + d };
  // let ans = ans % (2 * d);
  // let ans = if ans < d { ans } else { 2 * d - ans };
  w!(writer; ans);
}

t!(tc1 => r"6 2 4", r"2");
t!(tc2 => r"7 4 3", r"1");
t!(tc3 => r"10 1 2", r"8");
t!(tc4 => r"1000000000000000 1000000000000000 1000000000000000", r"1000000000000000");
t!(tc5 => r"8 4 3", r"2");
t!(tc6 => r"9 4 3", r"3");
t!(tc7 => r"6 4 3", r"0");
t!(tc8 => r"5 4 3", r"1");


use std::io::{stderr, stdin, stdout, BufReader, BufWriter, Cursor, Read, Write};
use std::iter::Iterator;
use std::str::FromStr;
use std::cmp::min;
// use std::slice::Iter;
// use std::vec::IntoIter;

#[allow(dead_code)]
fn main() {
  let stdin = stdin();
  let r = &mut BufReader::new(stdin.lock());
  let stdout = stdout();
  let w = &mut BufWriter::new(stdout.lock());
  let stderr = stderr();
  let err = &mut BufWriter::new(stderr.lock());
  run(r, w, err);
  w.flush().unwrap();
  err.flush().unwrap();
}

macro_rules! _ft { () => (impl FnOnce(&mut Cursor<Vec<u8>>, &mut Vec<u8>, &mut Vec<u8>)); }

#[allow(dead_code)]
fn test(input: &str, output: &str, f: _ft!()) {
  let r = &mut Cursor::new(input.as_bytes().to_vec());
  let w: &mut Vec<u8> = &mut Vec::new();
  let err: &mut Vec<u8> = &mut Vec::new();
  f(r, w, err);
  let mut stderr = stderr();
  writeln!(stderr, "{}", String::from_utf8(err.to_vec()).unwrap()).unwrap();
  stderr.flush().ok();
  assert_eq!(String::from_utf8(w.to_vec()).unwrap(), output)
}

#[allow(dead_code)]
macro_rules! t {
  ($f: ident => $input: expr, $output: expr) => (
    #[test]
    fn $f() { test($input, $output, run); }
  );
}

#[allow(unused_macros)]
macro_rules! args {
  ($($arg: expr),*) => ({
    let mut s = String::new();
    $(s += &format!("{} ", $arg);)*
    s.pop().unwrap();
    s
  });
}

#[allow(unused_macros)]
macro_rules! st {
  ($name: ident => $($p: ident : $t: ty),+) => (
    struct $name { $($p : $t),+ }
    impl FromStr for $name {
      type Err = ();
      fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut iter = s.split_whitespace();
        Ok(Self {
          $($p: iter.next().unwrap().parse::<$t>().unwrap(),)+
        })
      }
    }
  );
  ($name: ident => $($($p: ident),+: $t: ty);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($($p: ident),+: $($t: ty),+);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($p: ident),+: $t: ty) => (st!($name => $($p : $t),+););
  ($name: ident => $($p: ident),+: $($t: ty),+) => (st!($name => $($p : $t),+););
}

fn _read_iter<R: Read>(reader: &mut R) -> impl Iterator<Item=char> + '_ {
  reader.by_ref()
    .bytes()
    .map(|c| c.unwrap() as char)
    .skip_while(|c| c.is_whitespace())
}

#[allow(dead_code)]
fn read<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| !c.is_whitespace()).collect::<String>();
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read_line<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| c != &'\n').collect::<String>();
  let str = if str.ends_with('\r') { &str[0..str.len() - 1] } else { &str };
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read1<R: Read, T>(reader: &mut R, mut f: impl FnMut(char) -> T) -> T {
  f(_read_iter(reader).next().unwrap())
}

#[allow(dead_code)]
fn read1_line<R: Read, T>(reader: &mut R, f: impl FnMut(char) -> T) -> Vec<T> {
  _read_iter(reader).take_while(|c| c != &'\n').map(f).collect::<Vec<_>>()
}

/// 1要素読む
#[allow(unused_macros)]
macro_rules! r {
  ($stream: expr) => (read::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));

  ($stream: expr; $t: ty) => (read::<$t,  _>($stream));
  ($stream: expr; $($t: ty),+) => (($(r!($stream; $t)),*));

  ($stream: expr; $t: ty; 1~) => (read::<$t,  _>($stream) - 1);
  ($stream: expr; $($t: ty),+; 1~) => (($(r!($stream; $t) - 1),*));

  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| r!($stream; $t)).collect::<Vec<_>>());
  ($stream: expr; $t: ty; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

#[allow(unused_macros)]
macro_rules! r1 {
  ($stream: expr) => (read1($stream, |c| c));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $f: expr) => (read1($stream, $f));
  ($stream: expr; $f: expr; $n: expr) => ((0..$n).map(|_| r1!($stream, $f)).collect::<Vec<_>>());
  ($stream: expr; $f: expr; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r1!($stream; $f)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

/// 1行読む
#[allow(unused_macros)]
macro_rules! rl {
  ($stream: expr) => (read_line::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $t: ty) => (read_line::<$t,  _>($stream));
  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| rl!($stream; $t)).collect::<Vec<_>>());
}

macro_rules! _writes {
  ($stream: expr; $arg0: expr, $($arg: expr),*) => ({
    write!($stream, "{}", $arg0).ok();
    $(write!($stream, " {}", $arg).ok();)*
  });
}

/// write
#[allow(unused_macros)]
macro_rules! w {
  ($stream: expr) => (write!($stream, " ").ok());
  ($stream: expr; ) => (w!($stream));
  ($stream: expr, ) => (w!($stream));

  ($stream: expr; $arg: expr) => (write!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (w!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (_writes!($stream; $arg0, $($arg),+));
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (w!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (write!($stream, $($arg)*).ok());
}

/// write_line
#[allow(unused_macros)]
macro_rules! wl {
  ($stream: expr) => (writeln!($stream).ok());
  ($stream: expr, ) => (wl!($stream));
  ($stream: expr; ) => (wl!($stream));

  ($stream: expr; $arg: expr) => (writeln!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (wl!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => ({
    _writes!($stream; $arg0, $($arg),+);
    wl!($stream)
  });
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (wl!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (writeln!($stream, $($arg)*).ok());
}

/// write Vec
#[allow(unused_macros)]
macro_rules! w_vec {
  ($stream: expr; $vec: expr) => ({
    let mut iter = $vec.iter();
    match iter.next() { Some(&i) => { w!($stream, "{}", i); }, None => {}, }
    for &i in iter { w!($stream, " {}", i); }
  });
}

/// write_line Vec
#[allow(unused_macros)]
macro_rules! wl_vec {
  ($stream: expr; $vec: expr) => ({
    w_vec!($stream; $vec);
    wl!($stream)
  });
}

trait VecAlias<T> {
  fn select<U>(&self, f: impl FnMut(&T) -> U)  -> Vec<U>;
}

impl<T> VecAlias<T> for Vec<T> {
  fn select<U>(&self, mut f: impl FnMut(&T) -> U)  -> Vec<U> {
    self.iter().map(|i| f(i)).collect::<Vec<_>>()
  }
}

trait VecOrdAlias<T> {
  fn asc(&mut self);
  fn desc(&mut self);
}

impl<T: Ord> VecOrdAlias<T> for Vec<T> {
  fn asc(&mut self) { self.sort_unstable(); }
  fn desc(&mut self) { self.sort_unstable_by(|i, j| j.cmp(i)); }
}

#[allow(unused_macros)]
macro_rules! v {
  ($elem: expr; $n: expr) => (vec![$elem; $n as usize]);
  ($elem: expr; $h: expr, $w: expr) => (vec![vec![$elem; $w as usize]; $h as usize]);
}

#[allow(unused_macros)]
macro_rules! check_v {
  ($h: expr, $w: expr => $i: expr, $j: expr) => (
    $i >= 0 && $i < $h && $j >= 0 && $j < $w
  );
}

#[allow(unused_macros)]
macro_rules! check_get_v {
  ($($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if (check_v!($h, $w => $i, $j)) { Some(($($vec[$i as usize][$j as usize],)+)) }
    else { None }
  );
  (up; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i - 1, $j)
  );
  (down; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i + 1, $j)
  );
  (left; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i, $j - 1)
  );
  (right; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    check_get_v!($($vec, )+; $h, $w => $i, $j + 1)
  );
}

#[allow(unused_macros)]
macro_rules! get_v {
  ($($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    ($($vec[$i as usize][$j as usize], )+)
  );

  (up; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $i > 0 { Some(($($vec[($i - 1) as usize][$j as usize],)+)) } else { None }
  );
  (down; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $i < $h - 1 { Some(($($vec[($i + 1) as usize][$j as usize],)+)) } else { None }
  );
  (left; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $j > 0 { Some(($($vec[$i as usize][($j - 1)  as usize],)+)) } else { None }
  );
  (right; $($vec: expr),+; $h: expr, $w: expr => $i: expr, $j: expr) => (
    if $j < $w - 1 { Some(($($vec[$i as usize][($j + 1) as usize],)+)) } else { None }
  );
}

#[allow(dead_code)]
struct Point<T> { i: T, j: T }

#[allow(unused_macros)]
macro_rules! pos {
  ($i: expr, $j: expr) => (Point { i: $i, j: $j });
  (up; $i: expr, $j: expr) => (pos!($i - 1, $j));
  (down; $i: expr, $j: expr) => (pos!($i + 1, $j));
  (left; $i: expr, $j: expr) => (pos!($i, $j - 1));
  (right; $i: expr, $j: expr) => (pos!($i, $j + 1));
}

#[allow(unused_variables)]
fn run<R: Read, W: Write, E: Write>(reader: &mut R, writer: &mut W, err: &mut E) {
  let (x, k, d) = r!(reader; i64, i64, i64);
  let x = x.abs();
  if k == 1 { w!(writer; min(x, (x - d).abs())); return; }
  if x / k >= d { w!(writer; x - k * d); return; }
  let mut ans = if k % 2 == 0 { x } else { x + d };
  // while ans > 0 { ans -= 2 * d; }
  // ans = -ans;
  let ans = ans % (2 * d);
  // wl!(err; ans);
  let ans = if ans < d { ans } else { 2 * d - ans };
  w!(writer; ans);
}

t!(tc1 => r"6 2 4", r"2");
t!(tc2 => r"7 4 3", r"1");
t!(tc3 => r"10 1 2", r"8");
t!(tc4 => r"1000000000000000 1000000000000000 1000000000000000", r"1000000000000000");
t!(tc5 => r"8 4 3", r"2");
t!(tc6 => r"9 4 3", r"3");
t!(tc7 => r"6 4 3", r"0");
t!(tc8 => r"5 4 3", r"1");


struct Scanner {
    private var elements = [String]()
    private var index = 0

    mutating func peek() -> String {
        while elements.count == index {
            elements = readLine()!.split(separator: " ").map(String.init)
            index = 0
        }
        return elements[index]
    }

    mutating func next() -> String {
        let value = peek()
        index += 1
        return value
    }

    mutating func nextInt() -> Int {
        return Int(next())!
    }

    mutating func nextDouble() -> Double {
        return Double(next())!
    }
}

var scanner = Scanner()
let X = abs(scanner.nextInt())
let K = scanner.nextInt()
let D = scanner.nextInt()

if Double(K) * Double(D) >= 1e18 || X <= K * D {
    let count = X / D
    if count % 2 == K % 2 {
        print(X - D * count)
    } else {
        print(D * (count + 1) - X)
    }
} else {
    print(X - K * D)
}


let l:[Int] = readLine()!.split(separator:" ").map{Int($0)!}
let x = abs(l[0]), k = l[1], d = l[2]
let m = x % d, n = x / d
print(k<n ? x-d*k : ((k-n)%2 == 0 ? m : d-m))


let startTime = Date()

import Foundation

let MOD = 10 ** 9 + 7
let alphabets = "abcdefghijklmnopqrstuvwxyz"
let ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let Yes = "Yes"
let No = "No"
prefix operator *
infix operator **: PowerPrecedence
precedencegroup PowerPrecedence {
    higherThan: MultiplicationPrecedence
    lowerThan: BitwiseShiftPrecedence
    associativity: right
}
prefix func * <T> (a: [T]) -> (T, T)             { return (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T)          { return (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T)       { return (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T)    { return (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { return (a[0], a[1], a[2], a[3], a[4], a[5]) }
func **(lhs: Int, rhs: Int) -> Int {
    return Int(pow(Double(lhs), Double(rhs)))
}
func **(lhs: Int, rhs: Double) -> Double {
    return pow(Double(lhs), rhs)
}
struct Stack<Element>: Collection {
    var items = [Element]()
    var startIndex: Int {
        return items.startIndex
    }
    var endIndex: Int {
        return items.endIndex
    }
    subscript(i: Int) -> Element {
        return items[i]
    }
    func index(after index: Int) -> Int {
        return items.index(after: index)
    }
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}
struct Queue<Element>: Collection {
    var items = [Element]()
    var startIndex: Int {
        return items.startIndex
    }
    var endIndex: Int {
        return items.endIndex
    }
    subscript(i: Int) -> Element {
        return items[i]
    }
    func index(after index: Int) -> Int {
        return items.index(after: index)
    }
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeFirst()
    }
}
struct Heap<Element: Comparable>: Collection {
    var items = [Element]()
    var startIndex: Int {
        return items.startIndex
    }
    var endIndex: Int {
        return items.endIndex
    }
    subscript(i: Int) -> Element {
        return items[i]
    }
    func index(after index: Int) -> Int {
        return items.index(after: index)
    }
    mutating func push(_ item: Element) {
        var i = items.count
        while i > 0 {
            let p = (i - 1) / 2
            if items[p] <= item {
                break
            }
            if i == items.count {
                items.append(items[p])
            } else {
                items[i] = items[p]
            }
            i = p
        }
        if i == items.count {
            items.append(item)
        } else {
            items[i] = item
        }
    }
    mutating func pop() -> Element {
        let ret = items[0]
        let x = items[items.endIndex]
        var i: Int = 0
        while i * 2 + 1 < items.endIndex {
            var a = i * 2 + 1
            let b = i * 2 + 2
            if b < items.endIndex && items[b] < items[a] {
                a = b
            }
            if items[a] >= x {
                break
            }
            items[i] = items[a]
            i = a
        }
        items[i] = x
        items.removeLast()
        return ret
    }
}
extension Collection {
    func count(where predicate: (Element) -> Bool) -> Int {
        return self.reduce(0){$0+(predicate($1) ? 1 : 0)}
    }
}
extension Collection where Element: Equatable {
    func count(of value: Element) -> Int {
        return self.reduce(0){$0+($1==value ? 1 : 0)}
    }
}
extension Array {
    func indices(where predicate: (Element) -> Bool) -> [Int] {
        return (0..<self.count).filter{predicate(self[$0])}
    }
}
extension Array where Element: Equatable {
    func indices(of value: Element) -> [Int] {
        return (0..<self.count).filter{self[$0]==value}
    }
}
extension Array where Element: Hashable {
    func tally() -> Dictionary<Element, Int> {
        var dic = [Element: Int]()
        self.forEach{dic[$0, default: 0] += 1}
        return dic
    }
}
extension Array where Element == Int {
    // condition が "<=" なら lower_bound, ">=" なら upper_bound
    func binarySearch(_ key: Int, _ condition: (Int, Int) -> Bool) -> Int {
        var ng = -1
        var ok = self.count
        if !condition(ng, ok) {
            swap(&ng, &ok)
        }
        while abs(ok - ng) > 1 {
            let mid = (ok + ng) / 2
            if condition(key, self[mid]) {
                ok = mid
            } else {
                ng = mid
            }
        }
        return ok
    }
}
extension String {
    func replaceCharacter(from: Character, to: Character) -> String {
        return String(self.map{$0==from ? to : $0})
    }
    func replaceSubstring(from: String, to: String) -> String {
        return self.replacingOccurrences(of: from, with: to)
    }
    subscript(range: Range<Int>) -> String {
//        let start = self.index(self.startIndex, offsetBy: range.startIndex)
//        let end = self.index(start, offsetBy: range.endIndex - range.startIndex)
//        return String(self[start..<end])
        return String(Array(self)[range])
    }
    subscript(i: Int) -> Character {
//        return Character(self[i..<i+1])
        return Array(self)[i]
    }
}
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringsSplit(by separator: Character = " ") -> [String] {
    return readLine()!.split(separator: separator).map{String($0)}
}
func readIntsSplit(by separator: Character = " ") -> [Int] {
    return readLine()!.split(separator: separator).map{Int($0)!}
}
func gcd(_ x: Int, _ y: Int) -> Int {
    return y>0 ? gcd(y, x%y) : x
}
func lcm(_ x: Int, _ y: Int) -> Int {
    return x * y / gcd(x, y)
}
func primeNumbers(until n: Int) -> [Int] {
    var flags = Array(repeating: true, count: n+1)
    for i in 2...Int(n**0.5+0.5) {
        if flags[i] {
            for j in stride(from: i**2, to: n+1, by: i) {
                flags[j] = false
            }
        }
    }
    return (2...n).filter{flags[$0]}
}
func divisors(of n: Int) -> [Int] {
    var ret = [Int]()
    for i in 1...Int(n**0.5+0.5) {
        if n.isMultiple(of: i) {
            ret.append(i)
            if n/i != i {
                ret.append(n/i)
            }
        }
    }
    return ret.sorted()
}
func primeFactors(of n: Int) -> [Int] {
    var n = n
    if n == 1 {
        return [0, 1]
    } else if n == 2 {
        return [0, 0, 1]
    }
    var ret = Array(repeating: 0, count: n+1)
    for i in 2...Int(n**0.5+0.5) {
        while n.isMultiple(of: i) {
        ret[i] += 1
        n /= i
      }
    }
    if n != 1 {
        ret[n] = 1
    }
    return ret
}
func manhattanDist(_ x1: Int, _ y1: Int, _ x2: Int, _ y2: Int) -> Int {
    return abs(x1 - x2) + abs(y1 - y2)
}
func euclideanDist(_ x1: Int, _ y1: Int, _ x2: Int, _ y2: Int) -> Double {
    return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
}
func elapsedTime() -> Double {
    return Date().timeIntervalSince(startTime)
}

/****************************** メインプログラム ******************************/

var (X, K, D) = *readIntsSplit().map{abs($0)}

if X/D >= K {
    print(X-D*K)
} else {
    if (K-X/D).isMultiple(of: 2) {
        print(X-X/D*D)
    } else {
        print(abs(X-X/D*D-D))
    }
}


import Foundation
let main: () = {
    let (X, K, D) = *listOfInt()
    let A = abs(X)
    let n = min(K, A / D)
    var ans = A - (K * D)
    let k = K - n
    if k % 2 > 0 { ans = D - ans }
    print(ans)
}()

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

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

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

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}

public class PriorityQueue<T> {
    private final var _heap: [T]
    private let compare: (T, T) -> Bool
    public init(_ compare: @escaping (T, T) -> Bool) {
        _heap = []
        self.compare = compare
    }
    public func push(_ newElement: T) {
        _heap.append(newElement)
        _ = siftUp(index: _heap.endIndex - 1)
    }
    public func peek() -> T? {
        if _heap.count == 0 { return nil }
        return _heap[0]
    }
    public func pop() -> T? {
        if _heap.count == 0 { return nil }
        _heap.swapAt(0, _heap.endIndex - 1)
        let pop = _heap.removeLast()
        _ = siftDown(index: 0)
        return pop
    }
    private func siftDown(index: Int) -> Bool {
        let left = index * 2 + 1
        let right = index * 2 + 2
        var smallest = index
        if left < _heap.count && compare(_heap[left], _heap[smallest]) { smallest = left }
        if right < _heap.count && compare(_heap[right], _heap[smallest]) { smallest = right }
        if smallest != index {
            _heap.swapAt(index, smallest)
            _ = siftDown(index: smallest)
            return true
        }
        return false
    }
    private func siftUp(index: Int) -> Bool {
        if index == 0 { return false }
        let parent = (index - 1) >> 1
        if compare(_heap[index], _heap[parent]) {
            _heap.swapAt(index, parent)
            _ = siftUp(index: parent)
            return true
        }
        return false
    }
}
extension PriorityQueue {
    public var count: Int { return _heap.count }
    public var isEmpty: Bool { return _heap.isEmpty }
    public func update<T2>(element: T2) -> T? where T2: Equatable {
        assert(element is T)  // How to enforce this with type constraints?
        for (index, item) in _heap.enumerated() {
            if (item as! T2) == element {
                _heap[index] = element as! T
                if siftDown(index: index) || siftUp(index: index) { return item }
            }
        }
        return nil
    }
    public func remove<T2>(element: T2) -> T? where T2: Equatable {
        assert(element is T)  // How to enforce this with type constraints?
        for (index, item) in _heap.enumerated() {
            if (item as! T2) == element {
                _heap.swapAt(index, _heap.endIndex - 1)
                _heap.removeLast()
                _ = siftDown(index: index)
                return item
            }
        }
        return nil
    }
    public var heap: [T] { return _heap }
    public func removeAll() { _heap.removeAll() }
    public func addAll(_ elements: [T]) { for e in elements { self.push(e) } }
}


import Foundation
let main: () = {
    let (X, K, D) = *listOfInt()
    let A = abs(X)
    let n = A / D
    var ans = A - (K * D)
    let k = K - n
    if k % 2 > 0 { ans = abs(ans - D) }
    print(ans)
}()

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

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

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

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}

public class PriorityQueue<T> {
    private final var _heap: [T]
    private let compare: (T, T) -> Bool
    public init(_ compare: @escaping (T, T) -> Bool) {
        _heap = []
        self.compare = compare
    }
    public func push(_ newElement: T) {
        _heap.append(newElement)
        _ = siftUp(index: _heap.endIndex - 1)
    }
    public func peek() -> T? {
        if _heap.count == 0 { return nil }
        return _heap[0]
    }
    public func pop() -> T? {
        if _heap.count == 0 { return nil }
        _heap.swapAt(0, _heap.endIndex - 1)
        let pop = _heap.removeLast()
        _ = siftDown(index: 0)
        return pop
    }
    private func siftDown(index: Int) -> Bool {
        let left = index * 2 + 1
        let right = index * 2 + 2
        var smallest = index
        if left < _heap.count && compare(_heap[left], _heap[smallest]) { smallest = left }
        if right < _heap.count && compare(_heap[right], _heap[smallest]) { smallest = right }
        if smallest != index {
            _heap.swapAt(index, smallest)
            _ = siftDown(index: smallest)
            return true
        }
        return false
    }
    private func siftUp(index: Int) -> Bool {
        if index == 0 { return false }
        let parent = (index - 1) >> 1
        if compare(_heap[index], _heap[parent]) {
            _heap.swapAt(index, parent)
            _ = siftUp(index: parent)
            return true
        }
        return false
    }
}
extension PriorityQueue {
    public var count: Int { return _heap.count }
    public var isEmpty: Bool { return _heap.isEmpty }
    public func update<T2>(element: T2) -> T? where T2: Equatable {
        assert(element is T)  // How to enforce this with type constraints?
        for (index, item) in _heap.enumerated() {
            if (item as! T2) == element {
                _heap[index] = element as! T
                if siftDown(index: index) || siftUp(index: index) { return item }
            }
        }
        return nil
    }
    public func remove<T2>(element: T2) -> T? where T2: Equatable {
        assert(element is T)  // How to enforce this with type constraints?
        for (index, item) in _heap.enumerated() {
            if (item as! T2) == element {
                _heap.swapAt(index, _heap.endIndex - 1)
                _heap.removeLast()
                _ = siftDown(index: index)
                return item
            }
        }
        return nil
    }
    public var heap: [T] { return _heap }
    public func removeAll() { _heap.removeAll() }
    public func addAll(_ elements: [T]) { for e in elements { self.push(e) } }
}


import * as fs from "fs";

// inputで受け取り配列化する
const [X, K, D] = fs.readFileSync("/dev/stdin", "utf8").split(" ").map(Number);

const temp = K * D;

if (temp > Math.abs(X)) {
  const x = Math.abs(X);
  const num = Math.floor(x / D);
  const diff = K - num;
  const ans = Math.min(Math.abs(X - num * D), Math.abs(X + num * D));
  if (diff % 2 === 0) {
    console.log(ans);
  } else {
    console.log(Math.min(Math.abs(ans + D), Math.abs(ans - D)));
  }
} else {
  const ans = Math.abs(X) - temp;
  console.log(ans);
}


import { readFileSync } from 'fs'

function main(input: string) {
  let [x, k, d] = input.split(' ').map(Number)
  x = Math.abs(x)

  const count = Math.min(k, Math.floor(x / d))
  const pos = x - count * d

  const result = (k - count) % 2 === 0 ? pos : d - pos

  console.log(result)
}

main(readFileSync('/dev/stdin', 'utf8').trim())


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var x: number;
    var k: number;
    var d: number;
    var ans: number;
    // init
    [x, k, d] = input.shift().split(" ").map(x => Number(x));
    // solve
    x = Math.abs(x);
    if (k < x / d) {
        ans = x - d * k;
    } else {
        var m = x % d;
        var n = (x - m) / d;
        if (k % 2 == n % 2) {
            ans = m;
        } else {
            ans = d - m;
        }
    }
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


import * as fs from "fs";

// inputで受け取り配列化する
const [X, K, D] = fs.readFileSync("/dev/stdin", "utf8").split(" ").map(Number);

const temp = K * D;

if (temp > X) {
  const x = Math.abs(X);
  const num = Math.floor(x / D);
  const diff = K - num;
  const ans = Math.min(Math.abs(X - num * D), Math.abs(X + num * D));
  if (diff % 2 === 0) {
    console.log(ans);
  } else {
    console.log(Math.min(Math.abs(ans + D), Math.abs(ans - D)));
  }
} else {
  console.log(X - temp);
}


import * as fs from "fs";

// inputで受け取り配列化する
const [X, K, D] = fs.readFileSync("/dev/stdin", "utf8").split(" ").map(Number);

const temp = K * D;

if (temp > X) {
  const x = Math.abs(X);
  const num = Math.floor(x / D);
  const diff = K - num;
  if (diff % 2 === 0) {
    console.log(Math.abs(x - num * D));
  } else {
    console.log(Math.min(Math.abs(x - num * D + D), Math.abs(x - num * D - D)));
  }
} else {
  console.log(X - temp);
}


// C - Walking Takahashi
import { readFileSync } from 'fs';
const input = readFileSync('/dev/stdin', 'utf8');

const [X, K, D] = input.split(' ').map((i) => parseInt(i));

let now = X;

for (let i = 0; i <= Math.log(K); i++) {
  const plus = now + D;
  const minus = now - D;
  if (Math.abs(plus) <= Math.abs(minus)) {
    now = plus;
  } else {
    now = minus;
  }
}

console.log(now);


a=int(input())
b=sorted(map(int,input().split()))
print(b[-1]-b[0])


N = int(input())
x = sorted(map(int,input().split()))
print(abs(x[-1]-x[0]))


N = input()
A=sorted(map(int,input().split()),reverse = True)
s = A[0]-A[-1]
print(s)


n = int(input())
min_A = 10**9+7
max_A = -1
for i in range(n):
  tmp = int(input())
  max_A = max(tmp,max_A)
  min_A = min(min_A,tmp)

print(abs(max_A-min_A))


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

print(max(N) - min(N))


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

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


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

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int N = sc.nextInt();
		int min = Integer.MAX_VALUE;
		int max = 0;
		for (int i = 0; i < N; i++) {
			int a = sc.nextInt();
			min = Math.min(min, a);
			max = Math.max(max, a);
		}
		System.out.println(max - min);
	}

	private static class Is {
		int a;
		int b;
		Is (int a, int b) {
			this.a = a;
			this.b = b;
		}
	}

	public static long gcd(long a, long b) {
		long remainder = a % b;
		if (remainder == 0) {
			return b;
		} else {
			return gcd(b, remainder);
		}
	}
}

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());
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;

	void solve() throws IOException {
		int[] a = nia( ni());
		Arrays.sort(a);
		out.println(a[a.length-1]-a[0]);
	}

	String ns() throws IOException {
		while (!tok.hasMoreTokens()) {
			tok = new StringTokenizer(in.readLine(), " ");
		}
		return tok.nextToken();
	}

	int ni() throws IOException {
		return Integer.parseInt(ns());
	}

	long nl() throws IOException {
		return Long.parseLong(ns());
	}

	double nd() throws IOException {
		return Double.parseDouble(ns());
	}

	String[] nsa(int n) throws IOException {
		String[] res = new String[n];
		for (int i = 0; i < n; i++) {
			res[i] = ns();
		}
		return res;
	}

	int[] nia(int n) throws IOException {
		int[] res = new int[n];
		for (int i = 0; i < n; i++) {
			res[i] = ni();
		}
		return res;
	}

	long[] nla(int n) throws IOException {
		long[] res = new long[n];
		for (int i = 0; i < n; i++) {
			res[i] = nl();
		}
		return res;
	}

	public static void main(String[] args) throws IOException {
		in = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		tok = new StringTokenizer("");
		Main main = new Main();
		main.solve();
		out.close();
	}
}


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

public class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int[] a = sc.nextIntList(n);
        int max = 1; int min = (int)Math.pow(10,9);
        for (int i : a) {
            if (i > max) {
                max = i;
            }
            if (i < min) {
                min = i;
            }
        }
        System.out.println(max-min);
    }
}

class FastScanner {
    public static String debug = null;

    private final InputStream in = System.in;
    private int ptr = 0;
    private int buflen = 0;
    private byte[] buffer = new byte[1024];
    private boolean eos = false;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                if (debug != null) {
                    buflen = debug.length();
                    buffer = debug.getBytes();
                    debug = "";
                    eos = true;
                } else {
                    buflen = in.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen < 0) {
                eos = true;
                return false;
            } else 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;
    }

    private void skipUnprintable() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
    }

    public boolean isEOS() {
        return this.eos;
    }

    public boolean hasNext() {
        skipUnprintable();
        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() {
        return (int) nextLong();
    }

    public long[] nextLongList(int n) {
        return nextLongTable(1, n)[0];
    }

    public int[] nextIntList(int n) {
        return nextIntTable(1, n)[0];
    }

    public long[][] nextLongTable(int n, int m) {
        long[][] ret = new long[n][m];
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                ret[i][j] = nextLong();
            }
        }
        return ret;
    }

    public int[][] nextIntTable(int n, int m) {
        int[][] ret = new int[n][m];
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                ret[i][j] = nextInt();
            }
        }
        return ret;
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int[] numbers = new int[N];

		for(int j = 0; j <numbers.length; j++) {
			numbers[j] = sc.nextInt();
		}

		int max = numbers[0];
		int min = numbers[0];

		for(int i = 1; i < 4; i++ ) {
			if(numbers[i] > max ) {
				max = numbers[i];
			}
			if(numbers[i] < min ) {
				min = numbers[i];
			}
		}
		System.out.println(max-min);
	}

}


import java.util.*; import java.io.*; import java.math.*;
public class Main{
	//Don't have to see. start------------------------------------------
	static class InputIterator{
		ArrayList<String> inputLine = new ArrayList<String>(1024);
		int index = 0; int max; String read;
		InputIterator(){
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			try{
				while((read = br.readLine()) != null){
					inputLine.add(read);
				}
			}catch(IOException e){}
			max = inputLine.size();
		}
		boolean hasNext(){return (index < max);}
		String next(){
			if(hasNext()){
				return inputLine.get(index++);
			}else{
				throw new IndexOutOfBoundsException("There is no more input");
			}
		}
	}
	static HashMap<Integer, String> CONVSTR = new HashMap<Integer, String>();
	static InputIterator ii = new InputIterator();//This class cannot be used in reactive problem.
	static PrintWriter out = new PrintWriter(System.out);
	static void flush(){out.flush();}
	static void myout(Object t){out.println(t);}
	static void myerr(Object t){System.err.print("debug:");System.err.println(t);}
	static String next(){return ii.next();}
	static boolean hasNext(){return ii.hasNext();}
	static int nextInt(){return Integer.parseInt(next());}
	static long nextLong(){return Long.parseLong(next());}
	static double nextDouble(){return Double.parseDouble(next());}
	static ArrayList<String> nextStrArray(){return myconv(next(), 8);}
	static ArrayList<String> nextCharArray(){return myconv(next(), 0);}
	static ArrayList<Integer> nextIntArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Integer> ret = new ArrayList<Integer>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Integer.parseInt(input.get(i)));
		}
		return ret;
	}
	static ArrayList<Long> nextLongArray(){
		ArrayList<String> input = nextStrArray(); ArrayList<Long> ret = new ArrayList<Long>(input.size());
		for(int i = 0; i < input.size(); i++){
			ret.add(Long.parseLong(input.get(i)));
		}
		return ret;
	}
	static String myconv(Object list, int no){//only join
		String joinString = CONVSTR.get(no);
		if(list instanceof String[]){
			return String.join(joinString, (String[])list);
		}else if(list instanceof ArrayList){
			return String.join(joinString, (ArrayList)list);
		}else{
			throw new ClassCastException("Don't join");
		}
	}
	static ArrayList<String> myconv(String str, int no){//only split
		String splitString = CONVSTR.get(no);
		return new ArrayList<String>(Arrays.asList(str.split(splitString)));
	}
	public static void main(String[] args){
		CONVSTR.put(8, " "); CONVSTR.put(9, "\n"); CONVSTR.put(0, "");
		solve();flush();
	}
	//Don't have to see. end------------------------------------------
	static void solve(){//Here is the main function
      int N = nextInt();
      ArrayList<Integer> list = new ArrayList<Integer>();
      int max = 0;
      for(int i = 0; i < N - 1; i++){
        for(int j = i + 1; j < N; i++){
          max = Math.max(max, Math.abs(list.get(i) - list.get(j)));
        }
      }
      myout(max);
	}
	//Method addition frame start

	//Method addition frame end
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;

public class Main {
	public static void main(String[] args) {
		for(int i=0;i<1;i++) {
			slover();
			out.flush();
		}
	}
	static FastScanner sc = new FastScanner();
	static PrintWriter out = new PrintWriter(System.out);
	//StringBuffer S = new StringBuffer(sc.next());
		//String hoge2 = str.reverse().toString();
		//map.containsKey(A)
		//Map<Integer, Integer> map = new HashMap<Integer, Integer>(N);
		/*for ( キーのデータ型 key : マップの名前.keySet() ) {
			データのデータ型 data = マップの名前.get( key );

			// keyやdataを使った処理;
		}*/
		//int i = Integer.parseInt(s);
		//Queue<String> qq=new ArrayDeque<>(); //add,poll,peek BFSは前から実行される
		//Deque<String> dd=new ArrayDeque<>();//push後ろに入れる,poll(pop)後ろからとる,peek addは先頭に入るからバグ注意
		//stackdfsは後ろから実行される
		//ArrayList<Integer> cc = new ArrayList<>(N);
		//cc.contains(tmp)
		//Arrays.asList(c).contains("a")
		//list.set(1,"walk");//1 1 2 3 5

		private static int INF =1000000007;

		private static class D{
			int a,b,c;

			D(int a,int b,int c){
				this.a=a;;
				this.b=b;
				this.c=c;

			}

		}

	//Set<Long> a=new HashSet<Long>();
	private static int mod=1000000007;

	private static ArrayList<Long> divisors2(long t) {
		ArrayList<Long> c=new ArrayList<>();
		for(int i=1;i*i<=t;i++) {
			if(t%i==0) {
				if(i*i!=t) {
					c.add(t/i);
				}

				c.add((long)i);
			}
		}
		Collections.sort(c);
		Collections.reverse(c);
		return c;
	}

	private static int slover()   {

		int N=sc.nextInt();
		int a[]=sc.nextIntArray(N, false);
		int ans=mod;
		for(int i=0;i<N;i++) {
			for(int t=0;t<N;t++) {
				if(i==t)continue;
				ans=Math.max(ans, Math.abs(a[i]-a[t]));
			}
		}

		p(ans);

		return 0;
	}
	private static int modPow2(String S,int mod) {
		//iのt乗をO(log t)で返す
		int a=2;
		int res=1;
		int N=S.length()-1;
		for(int i=0;i<S.length();i++) {
			if(S.charAt(N-i)=='1') {
				res=res*a%mod;
			}
			a=a*a%mod;
		}
		return res;
	}
	private static long modPow(int i,int t,long mod) {
		//iのt乗をO(log t)で返す
		long a=i;
		long res=1;
		while(t!=0) {
			//p(t);
			if((1&t)==1) {
				res=res*a%mod;
			}
			a=a*a%mod;
			t=t>>1;
		}
		return res;
	}
	public static int pid(int i) {
		int t=0;
		int j=0;
		while((i>>j)!=0) {
			if((1&(i>>j))==1) {
				t++;
			}
			j++;
		}
		return i%t;
	}
	public static long gcd(long num1,long num2) {
        if(num2==0) return num1;
        else return gcd(num2,num1%num2);
    }
	public static long lcm(long num1,long num2) {
		return num1*num2/gcd(num1,num2);
	}
	//O(N^0.5)
	private static boolean isPrime(long t) {
		if(t<2)return false;
		for(int i=2;i*i<=t;i++) {
			if(t%i==0)return false;
		}
		return true;
	}
	private static ArrayList<Long> divisors(long t) {
		ArrayList<Long> c=new ArrayList<>();
		for(int i=1;i*i<=t;i++) {
			if(t%i==0) {
				if(i*i!=t) {
					c.add(t/i);
				}
				c.add((long)i);
			}
		}
		return c;
	}
	private static void bubunwa() {
		int N=sc.nextInt();
		int K=sc.nextInt();
		int a[]=sc.nextIntArray(N, false);

		boolean dp[] =new boolean[K+1];

		Arrays.fill(dp, false);
		dp[0]=true;
		for(int i=0;i<N;i++) {
			for(int x=K-a[i];x>=0;x--) {
				if(dp[x])dp[x+a[i]]=true;
			}
		}

		p(dp[K] ? "Yes":"No");
	}

	private static String bitToString(int i) {

			String T="";
			for(int j=0;j<2;j++) {
				//if(i>>j==0)break;
				if((1&i>>j)==1) {
					T+="1";
				}else T+="0";
			}
			return (i+" "+T);

	}
/*********************************************************************/
	//target以下までの値のindexを返す
	//target以上が欲しいときは返り値+1すればいい
	//0-indexで個数を求めるときはさらにindex+1する必要あり
	private static int lower_bound(long a[],long target) {
	//p(target+ " "+Arrays.toString(a));
	if(a[0]>target)return -1;
	//最後の値がtarget以下であるときは最後のindexを返す。
	//target以上が欲しいときは注意する必要あり
	if(a[a.length-1]<=target) return a.length-1;

	int S=-1;
	int E=a.length;

	while(S<E) {

		int G=(S+E)/2;
		if(G+1==a.length) {
			G--;
		}
		//未満にしたいときは=の場所を変える
		if(a[G]<=target&&a[G+1]>target) {
			return G;

		}else if(a[G]<=target){
			S=G;
		}else if(a[G]>target) {
			E=G;
		}

	}

	return -1;
	}
	static String nextPermutation(String s) {
		ArrayList<Character> list=new ArrayList<>();
		for(int i=0;i<s.length();i++) {
			list.add(s.charAt(i));
		}
		int pivotPos=-1;
		char pivot=0;
		for(int i=list.size()-2;i>=0;i--) {
			if(list.get(i)<list.get(i+1)) {
				pivotPos=i;
				pivot=list.get(i);
				break;
			}
		}
		if(pivotPos==-1&&pivot==0) {
			return "Final";
		}
		int L=pivotPos+1,R=list.size()-1;

		int minPos=-1;
		char min =Character.MAX_VALUE;

		for(int i=R;i>=L;i--) {
			if(pivot<list.get(i)) {
				if(list.get(i)<min) {
					min=list.get(i);
					minPos=i;
				}
			}
		}

		Collections.swap(list, pivotPos, minPos);
		Collections.sort(list.subList(L, R+1));

		StringBuilder sb=new StringBuilder();
		for(int i=0;i<list.size();i++) {
			sb.append(list.get(i));
		}
		return sb.toString();
	}
private static long[][] com;
private static void nCr() {
	int MAX = 3001;
	com= new long[MAX][MAX];
	for(int i = 0; i < MAX; i++)
	    com[i][0] = 1;
	for(int i = 1; i < MAX; i++) {
	    for(int j = 1; j <= i; j++) {
	        com[i][j] = com[i-1][j-1] + com[i-1][j];
	        com[i][j] %= mod;
	    }
	}
}

	static void p(String ans) {out.println(ans);};
	static void p(int ans) {out.println(ans);};
	static void p() {out.println();};
	static void p(long ans) {out.println(ans);};
	static void p(double ans) {out.println(ans);};

	static void pn(String ans) {out.print(ans);};
	static void pn(int ans) {out.print(ans);};
	static void pn() {out.print("");};
	static void pn(long ans) {out.print(ans);};
	static void pn(double ans) {out.print(ans);};

	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;
	    }

	    private void skipUnprintable() {
	      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
	    }

	    public boolean hasNext() {
	      skipUnprintable();
	      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() {
	      return (int) nextLong();
	    }

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

	    public int[] nextIntArray(int N, boolean oneBased) {
	      if (oneBased) {
	        int[] array = new int[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      } else {
	        int[] array = new int[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextInt();
	        }
	        return array;
	      }
	    }

	    public long[] nextLongArray(int N, boolean oneBased) {
	      if (oneBased) {
	        long[] array = new long[N + 1];
	        for (int i = 1; i <= N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      } else {
	        long[] array = new long[N];
	        for (int i = 0; i < N; i++) {
	          array[i] = sc.nextLong();
	        }
	        return array;
	      }
	    }
	  }
}


#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    int n,sum;
    int a[105];
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    sort(a,a+n);
    sum=a[n-1]-a[0];
    printf("%d\n",sum);
    return 0;
}


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

int main(void) {
    int N;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) {
        cin >> A[i];
    }
    sort(A.begin(), A.end());
    cout << A[N - 1] - A[0];
    return 0;
}


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

 int main(){
    int N;
    int i;
    int A[120];
    int ans = 0;
    int min, max;

    cin >> N;
    for(i=0; i<N; i++)
        cin >> A[i];
    min = A[0];
    max = A[0];

    for(i=1; i<N; i++){
        if (A[i] > max)
            max=A[i];
        if (A[i] < min)
            min=A[i];
        }
    ans = max - min;

    cout << ans << endl;
    return 0;
 }


#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a.at(i);
    }
    int MAX = 0;
    int MIN = 0;
    for (int i = 0; i < n; i++) {
        if (i == 0) {
            MAX = a.at(0);
            MIN = a.at(0);
            continue;
        }
        MAX = max(a.at(i), MAX);
        MIN = min(a.at(i), MIN);
    }
    cout << MAX - MIN << endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a.at(i);
    }
    int MAX = 0;
    int MIN = 0;
    for (int i = 0; i < n; i++) {
        if (i = 0) {
            MAX = a.at(0);
            MIN = a.at(0);
            continue;
        }
        MAX = max(a.at(i), MAX);
        MIN = min(a.at(i), MIN);
    }
    cout << MAX - MIN << endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a.at(i);
    }
    int MAX = 0;
    int MIN = 0;
    for (int i = 0; i < n; i++) {
        if (i = 0) {
            MAX = a.at(0);
            MIN = a.at(0);
            break;
        }
        MAX = max(a.at(i), MAX);
        MIN = min(a.at(i), MIN);
    }
    cout << MAX - MIN << endl;
    return 0;
}


#include <stdio.h>

int main()
{
    int n, a[100+1], i, j, min, max;

    scanf( "%d", &n );
    for( i =  1; i < n+1; i++ )
    {
        scanf( "%d", &a[i] );
    }

    //最大と最小を見つけて差を出す
    min = a[1];
    max = a[1];
    for( j = 1; j < n+1; j++ )
    {
        if( a[j] > max ) max = a[j];
        else if( a[j] < min ) min = a[j];
    }
    printf("%d\n", max - min);

    return 0;
}


#include <stdio.h>
int main() {
long long a, i, b, c;
long long x[100];
scanf("%lld", &a);
for (i = 0;i < a;i++) {
scanf("%lld", &x[i]);
} b = x[0];
  c = x[0];
for (i = 1;i < a;i++) {
if (x[i] >= b) b = x[i];
} for (i = 1;i < a;i++) {
if (x[i] <= c) c = x[i];
} printf("%lld\n", b - c);
return 0;
}