Dynamic programming solution for array path