We are given numbers. We have to select of them. We also have a number . Suppose the numbers we selected were . (note that we write these numbers in order in which they appeared in the original array). Define .
We have to maximize .
Constraints :
Example:
Input: 7 4 3
4 9 8 2 6 7 4
Output:32
Approach
Java
import java.util.Arrays;public class WeirdSum {public static void main(String[] args) {int n = 7;int k = 4;int m = 3;int[] a = { 4, 9, 8, 2, 6, 7, 4 };long[][] dp = new long[k][2];long min = Long.MIN_VALUE / 100;for (int i = 0; i < dp.length; i++) {Arrays.fill(dp[i], min);}int current = 0;dp[0][current] = a[0] * (1 % m);for (int i = 1; i < n; i++) {current = 1 - current;dp[0][current] = Math.max(dp[0][1 - current], a[i] * (1 % m));for (int j = 1; j < k && j <= i; j++) {dp[j][current] = Math.max(dp[j][1 - current], 1L * dp[j - 1][1 - current] + 1L * a[i] * ((j + 1) % m));}}System.out.println(dp[k - 1][current]);}}
No comments:
Post a Comment