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 Scala (2.13.1) (judge verdict: Accepted)

object Main extends App {
  @scala.annotation.tailrec
  def loop(pairs: List[(Int, Int)], k: Int, acc: Int): Int = pairs match {
    case _ if k <= 0 => acc
    case Seq() => acc
    case (i, j) :: xs if i <= k => loop(xs, k - i, acc + i * j)
    case (_, j) :: xs => loop(xs, 0, acc + k * j)
  }

  val sc = new java.util.Scanner(System.in)
  val A, B, C, K = sc.nextInt()
  println(loop(List(A, B, C).zip(List(1, 0, -1)), K, 0))
}