Skip to content

Instantly share code, notes, and snippets.

@nguyensinhtu
Last active February 22, 2023 09:32
Show Gist options
  • Save nguyensinhtu/9e9760f1d2b7af284b47ffe0ad381706 to your computer and use it in GitHub Desktop.
Save nguyensinhtu/9e9760f1d2b7af284b47ffe0ad381706 to your computer and use it in GitHub Desktop.
package abc;
import java.util.Arrays;
/**
* @author tu.nguyen12
*/
public class MinimumCost {
private int maxCost = 1000000009;
private int[] memo;
private int bruceForce(int at, int[] costs, int k) {
if (at == costs.length - 1) {
return costs[at];
}
if (at >= costs.length) {
return maxCost;
}
if (memo[at] != -1) {
return memo[at];
}
int min = maxCost;
for (int i = at + 1; i <= at + k; ++i) {
min = Math.min(min, bruceForce(i, costs, k));
}
memo[at] = costs[at] + min;
return memo[at];
}
private int bruceForceWithMemo(int[] costs, int k) {
memo = new int[costs.length];
Arrays.fill(memo, -1);
return bruceForce(0, costs, k) - costs[0];
}
private int dp(int[] cost, int k) {
int[] dp = new int[cost.length];
dp[0] = cost[0];
for (int i = 1; i < cost.length; i++) {
dp[i] = maxCost;
for (int j = i; j >= Math.max(i - k, 0); j--) {
dp[i] = Math.min(dp[j] + cost[i], dp[i]);
}
}
return dp[cost.length - 1] - cost[0];
}
int getMinimumCost(int[] costs, int k) {
// return bruceForceWithMemo(costs, k);
return dp(costs, k);
}
}
/**
class MinimumCostTest {
@Test
void getMinimumCost() {
MinimumCost solution = new MinimumCost();
assertEquals(6, solution.getMinimumCost(new int[]{1, 2, 3, 4}, 2));
assertEquals(7, solution.getMinimumCost(new int[]{4, 3, 9, 3, 1}, 2));
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment