Give this problem a try 1635. Coin Combinations I.
Example Code
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
FastScanner io = new FastScanner();
int n = io.nextInt(), x = io.nextInt();
int[] coins = new int[n];
for (int i = 0; i < n; i++) coins[i] = io.nextInt();
Arrays.sort(coins);
int[] dp = new int[x+1];
Arrays.fill(dp, 0);
dp[0] = 1;
// TLE on CSES if % MOD -> use -MOD
// USACO gives 2x time for Java
for (int i = 1; i <= x; i++) {
for (int j = 0; j < n; j++) {
if (coins[j] > i) break;
dp[i] += dp[i-coins[j]];
if (dp[i] >= MOD) dp[i] -= MOD;
}
}
io.println(dp[x]);
}
/**
RESERVED NUMBERS
*/
public static int MOD = 1_000_000_007;
/**
DATA STRUCTURES
*/
static class MultiSet {
static TreeMap<Integer, Integer> multiset = new TreeMap<>();
static void add(int x) {
multiset.putIfAbsent(x, 0);
multiset.put(x, multiset.get(x)+1);
}
static void remove(int x) {
multiset.putIfAbsent(x, 0);
multiset.put(x, multiset.get(x)-1);
if (multiset.get(x) <= 0) multiset.remove(x);
}
}
/**
IO
*/
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
// returns null if no more input
public String next() {
while (!st.hasMoreElements())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
public int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public void println() { System.out.println(); }
public void println(int x) { System.out.println(x); }
public void println(long x) { System.out.println(x); }
public void println(String s) { System.out.println(s); }
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.readLine());
return st.nextToken();
} catch (Exception e) { }
return null;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
}
Complexity Analysis
- Time Complexity: O(n*x)
- Space Complexity: O(n+x)
Sign-off
Congratulations on making it this far! Best of luck in your future competitions!