Algorithms – Domino Solitaire Algorithm

algorithmsdynamic programming

Problem Statement –

Problem Statement

Given a 2xN grid of numbers, the task is to find the most profitable tiling combination (each tile covers 2×1 cells; vertically or horizontally) covering all tiles.

I thought of approaching it in the greedy way, enqueuing the max possible for any cell, but it has a fallback that a low-profit choice at i, could yield a greater profit at i+n tiles.

So what should be the approach?

EDIT – Test Data Range – N<=105

Source – INOI 2008 Q Paper

UPDATE
Working out the plausibility of a Dynamic programming Approach.

UPDATE 2
Worked out an answer using DP.

Best Answer

Worked out a Dynamic Programming Approach to the problem -

int t[n][2]; //Stores grid values
int b[n]; //Stores best solution upto a particular column
b[0]= t[0][1]-t[0][0]; //Compute score for first column (Absolute Value)
b[1]= Max (b[0] + Score for column 1 vertically, Score for first 2 horizontal columns);
for i=0...n 
  b[i]= Max ( b[i-1] + Score for column i vertically, b[i-2] + Score for horizontal columns i & i-1);
print b[n-1];

Works efficiently on the given data set, with a linear time complexity!