[Baekjoon 2156] Wine Tasting with DP
A dynamic programming solution with states for the number of consecutive glasses consumed.
October 6, 2023
I solved Baekjoon 2156: Wine Tasting.
The goal is to maximize the amount of wine consumed without drinking three consecutive glasses. DP came to mind as soon as I read the problem.
Define the states
Let the wine array be grape, with length n.
- If
n == 1, the answer isgrape[0]. - If
n == 2, it isgrape[0] + grape[1].
For n >= 3, we must respect the limit of two consecutive glasses. I split the state at each position into 0, 1, and 2 consecutive glasses.
0: skip the current glass and take the maximum of the three previous states.1: drink this glass after skipping the preceding one.2: drink this glass after drinking exactly one consecutive glass.
The recurrence is:
dp[index][continueNum]
dp[index][0] = max(dp[index - 1][0], dp[index - 1][1], dp[index - 1][2])
dp[index][1] = dp[index - 1][0] + grape[index]
dp[index][2] = dp[index - 1][1] + grape[index]
Code
n = int(input())
grape = []
for _ in range(n):
grape.append(int(input()))
if n == 1:
print(grape[0])
elif n == 2:
print(grape[0] + grape[1])
else:
dp = [[0 for _ in range(3)] for _ in range(n)]
dp[0][1] = grape[0]
dp[0][2] = grape[0]
dp[1][0] = grape[0]
dp[1][1] = grape[1]
dp[1][2] = grape[0] + grape[1]
for i in range(2, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2])
dp[i][1] = dp[i - 1][0] + grape[i]
dp[i][2] = dp[i - 1][1] + grape[i]
print(max(dp[n - 1][0], dp[n - 1][1], dp[n - 1][2]))
This gave me a solution to the wine tasting problem.
Original post: View source