Skip to content

Instantly share code, notes, and snippets.

@AmosAidoo
Created October 30, 2019 19:17
Show Gist options
  • Save AmosAidoo/f06765044d005e64d403f36aa23c1d12 to your computer and use it in GitHub Desktop.
Save AmosAidoo/f06765044d005e64d403f36aa23c1d12 to your computer and use it in GitHub Desktop.
Some random problem I found in a WhatsApp group
public class FacebookProblem {
public static void main(String[] args) {
// TODO code application logic here
int A[][] = {
{5, 4, 4},
{4, 3, 4},
{3, 2, 4},
{2, 2, 2},
{3, 3, 4},
{1, 4, 4},
{4, 1, 1}
};
int answer = solution(A);
System.out.println(answer);
}
public static int solution(int A[][]) {
final int INVALID = 1000000009;
int pointer = 2;
int dp[][] = new int[A.length][A[0].length];
dp[0][0] = 1;
int last = A[0].length - 1, max = -1;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length; j++) {
int down,right;
down =(i+1 < A.length) ? A[i+1][j] : INVALID;
right = (j+1 <= last) ? A[i][j+1] : INVALID;
if (dp[i][j] > 0) {
if (A[i][j] == right) dp[i][j+1] = dp[i][j];
if (A[i][j] == down) dp[i+1][j] = dp[i][j];
} else {
dp[i][j] = pointer++;
if (A[i][j] == right) {
if (dp[i][j+1] > 0){
dp[i][j] = dp[i][j+1];
pointer--;
} else dp[i][j+1] = dp[i][j];
}
if (A[i][j] == down) dp[i+1][j] = dp[i][j];
}
max = Math.max(max, dp[i][j]);
}
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment