https://www.nowcoder.com/discuss/635066067198509056?sourceSSR=users public static int dynamic(int[] days, int[] costs) { int[] dp = new int[days[days.length - 1] + 1]; int index = 0; for (int i = 1; i < dp.length &amp;&amp; index < days.length; i++) { if (days[index] == i) { int min = Integer.MAX_VALUE; int costT = Integer.MAX_VALUE; int costW = Integer.MAX_VALUE; int costM = Integer.MAX_VALUE; int costD = dp[i - 1] + costs[0]; min = Math.min(min,costD); if (i - 3 > 0) costT = dp[i - 3] + costs[1]; min = Math.min(min,costT); if (i - 7 > 0) costW = dp[i - 7] + costs[2]; min = Math.min(min,costW); if (i - 30 > 0) costM = dp[i - 30] + costs[3]; min = Math.min(min,costM); dp[i] = min; index++; } else { dp[i] = dp[i - 1]; } } return dp[days[days.length - 1]]; }