One pass is indeed enough!
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * * @author Sanchit M. Bhatnagar * @see http://uhunt.felix-halim.net/id/74004 * */ public class P11683 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = null; String line; while ((line = br.readLine()) != null) { st = new StringTokenizer(line.trim()); int A = Integer.parseInt(st.nextToken()); if (A == 0) break; int B = Integer.parseInt(st.nextToken()); int[] sculpt = new int[B]; st = new StringTokenizer(br.readLine().trim()); int ans = 0; int last = -1; for (int i = 0; i < B; i++) { sculpt[i] = Integer.parseInt(st.nextToken()); if (last == -1) { last = sculpt[i]; if (sculpt[i] != A) ans += (A - sculpt[i]); } if (sculpt[i] >= last) { last = sculpt[i]; } else { ans += (last - sculpt[i]); last = sculpt[i]; } } out.println(ans); } out.close(); br.close(); } }