// Solution to "TwoEnds" by Bob Roos // // Dynamic programming -- maintain a table of max. differences in score for // each subsequence of the original sequence of numbers, updating the table // according to the greedy strategy for odd-length subsequences (player 2's // turn) and optimal strategy for even-length subsequences (player 1). import java.io.*; import java.util.*; public class TwoEnds { public static BufferedReader in; public static StringTokenizer tok; public static int[] board; public static int[][] grid; public static int gameNum; public static int n; public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); String line; gameNum = 0; while (!(line = in.readLine().trim()).equals("0")) { gameNum++; tok = new StringTokenizer(line); n = Integer.parseInt(tok.nextToken()); board = new int[n]; for (int i = 0; i < n; i++) board[i] = Integer.parseInt(tok.nextToken()); grid = new int[n][n]; fillIn(); System.out.println("In game " + gameNum + ", the greedy strategy " +"might lose by as many as "+grid[0][n-1]+" points."); } } public static void fillIn() { for (int i = 0; i < n-1; i++) grid[i][i+1] = Math.abs(board[i]-board[i+1]); for (int diag = 2; diag < n; diag++) { for (int i = 0; i < n - diag; i++) { if (diag%2 == 0) { // must be player 2's turn, so use greedy: int maxPos = i; if (board[i+diag] > board[i]) maxPos = i+diag; if (maxPos == i) grid[i][i+diag] = grid[i+1][i+diag]-board[maxPos]; else grid[i][i+diag] = grid[i][i+diag-1]-board[maxPos]; } else { int temp1 = board[i]+grid[i+1][i+diag]; int temp2 = board[i+diag]+grid[i][i+diag-1]; grid[i][i+diag] = Math.max(temp1,temp2); } } } } }