Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactored] : Update cses 1634 condition and format Python section #4789

Merged
merged 5 commits into from
Sep 17, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 13 additions & 21 deletions solutions/gold/cses-1634.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,8 @@ int main() {
for (int i = 0; i <= x; i++) { dp[i] = INT_MAX; }
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int weight = 0; weight <= x; weight++) {
if (weight - coins[i - 1] >= 0) {
dp[weight] = min(dp[weight], dp[weight - coins[i - 1]] + 1);
}
for (int weight = coins[i - 1]; weight <= x; weight++) {
dp[weight] = min(dp[weight], dp[weight - coins[i - 1]] + 1);
}
}
cout << (dp[x] == INT_MAX ? -1 : dp[x]) << '\n';
Expand Down Expand Up @@ -126,10 +124,8 @@ public class cses1634 {
If the state curWeight - coin[i] is possible
DP[curWeight] = min(DP[curWeight], DP[curWeight - coin[i]] + 1). */
for (int i = 1; i <= N; i++) {
for (int sum = 0; sum <= X; sum++) {
if (sum - coins[i - 1] >= 0) {
dp[sum] = Integer.min(dp[sum], dp[sum - coins[i - 1]] + 1);
}
for (int sum = coins[i - 1]; sum <= X; sum++) {
dp[sum] = Integer.min(dp[sum], dp[sum - coins[i - 1]] + 1);
}
}

Expand All @@ -144,8 +140,8 @@ public class cses1634 {
}
```
</JavaSection>

<PySection>

```py
INF = 1000000000 # Using float('inf') results in a TLE

Expand All @@ -155,21 +151,17 @@ c = list(map(int, input().split()))
dp = [INF] * (x + 1)
dp[0] = 0 # Base case: 0 coins are needed for a sum of 0

for i in range(x):
# Continue if the state is impossible
if i == INF:
continue
for coin in c:
if i + coin <= x:
"""
DP transition: state i needs dp[i] coins,
so state i + coin can be made with dp[i] + 1 coins.
"""
dp[i + coin] = min(dp[i + coin], dp[i] + 1)
for coin in c:
for i in range(x - coin + 1):
"""
DP transition: state i needs dp[i] coins,
so state i + coin can be made with dp[i] + 1 coins.
"""
dp[i + coin] = min(dp[i + coin], dp[i] + 1)


print(dp[x] if dp[x] != INF else -1)
```
</PySection>

</PySection>
</LanguageSection>
Loading