Problem:
Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000

Solution in OCaml (4.10.0) (judge verdict: Accepted)

open Batteries
open Printf
open Scanf

let ($) g f x = g (f x)
let nil = ()

module MyList = struct
  include List
  let foldl = fold_left
  let foldr = fold_right
  
  let flatmap f ls = concat @@ map f ls

  let zipf = map2
  let zipfi = map2i
end

module L = MyList

let atoi = int_of_string
let itoa = string_of_int
let atof = float_of_string
let ftoa = string_of_float
let ctoi = int_of_char
let itoc = char_of_int

let stocl = String.to_list
let cltos = String.of_list
let spsp s = String.split_on_char ' ' s

module MyString = struct
  include String

  let map' f s = L.map f (stocl s)
  let mapi' f s = L.map f (stocl s)

  let zipf f a b = L.zipf f (stocl a) (stocl b)
  let zipfi f a b = L.zipfi f (stocl a) (stocl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)
end

module S = MyString

let tup2 a b = (a, b)
let tup3 a b c = (a, b, c)
let tup4 a b c d = (a, b, c, d)

let rds () = read_line ()
let rds2 () = scanf "%s %s\n" tup2

let rdi () = atoi @@ rds ()
let rdi2 () = scanf "%d %d\n" tup2
let rdi3 () = scanf "%d %d %d\n" tup3
let rdi4 () = scanf "%d %d %d %d\n" tup4

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map atoi

let rdvs n rdf = L.init n (fun _ -> rdf ())

let rdvi n = rdvs n rdi
let rdvi2 n = rdvs n rdi2
let rdvi3 n = rdvs n rdi3
let rdvi4 n = rdvs n rdi4

let puts s = print_endline s
let putyn b = puts (if b then "Yes" else "No")
let puti i = puts @@ itoa i

let _ =
  let (a,b,c,k) = rdi4 () in
  let r =
    if k <= a + b then (min a k)
    else a - (k - (a + b))
  in puti r;;