CSES - Money Sums

Authors: Sofia Yang, Qian Qian

Table of Contents

ExplanationImplementation

Official Editorial

Explanation

For this problem, we'll define dp[i][j]\texttt{dp[i][j]} as if it is possible to make a sum of jj with ii coins.

And if we loop through all the coins and possible sums, then we'll get two possible situations:

If it is possible to make a sum of jj with less than ii coins, then make the same sum with more than ii coins will also be possible.

And if it is possible to make a sum of current_sum - coin_value[i]\texttt{current\_sum - coin\_value[i]} with i1i - 1 coins, then make a sum of current_sum\texttt{current\_sum} with ii coins will also be possible.

And at the end, we can loop through the dp\texttt{dp} array, find all the possible sums\texttt{sums} with nn coins, put them in a dynamic array, then print out the size of that dynamic array and every elements in it.

Implementation

Time Complexity: O(NX)\mathcal{O}(N\cdot X)

C++

#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100;
const int MAX_SUM = 1e5;
bool dp[MAX_N + 1][MAX_SUM + 1];
int main() {

Java

import java.io.*;
import java.util.*;
public class MoneySums {
public static int maxSum = (int)1e5;
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int N = io.nextInt();

Python

n = int(input())
money = list(map(int, input().split()))
max_sum = n * 1000
dp = [[False] * (max_sum + 1) for _ in range(n + 1)]
dp[0][0] = True
for i in range(1, n + 1):
for j in range(max_sum + 1):
dp[i][j] = dp[i - 1][j]

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!