Dynamic programming/Java