Give this problem a try 1634. Minimizing Coins.
Example Code
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
// Kattio io = new Kattio("");
FastScanner io = new FastScanner();
int n = io.nextInt(), x = io.nextInt();
int[] c = new int[n];
for (int i = 0; i < n; i++) c[i] = io.nextInt();
int[] dp = new int[x+1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= x; i++) {
for (int ci : c) {
if (i - ci >= 0 && dp[i-ci] != Integer.MAX_VALUE) {
dp[i] = Math.min(dp[i], dp[i-ci]+1);
}
}
}
io.println(dp[x] == Integer.MAX_VALUE ? -1 : dp[x]);
}
/**
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);
}
}
/**
UTILS
*/
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!