We have an array of N
elements. I have to choose K
elements from this array(you can't take an element with index that is greater than the index of the element of the next one) in such a way that the sum abs(a1-a0)+abs(a2-a1)+...+(ak-ak-1)
is maximized. My idea is 2d DP and goes like this: The solution that involves taking the n
-th element while having taken k
elements is the maximum of the solutions where element with index j
smaller than i
is the last one, j
from k-1
, j<i
plus taking the abs(numbers[n]-numbers[j])
. Here is my code. Where is my mistake?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class SumOfAbsoluteDifferences {
static int solve(int numbers[], int N, int K) {
int[][] dp = new int[N][K];
for (int i=0; i<N; i++) {
for (int j=0; j<K; j++)
dp[i][j] = 0;
}
int E = 1;
for (int i=0; i<N; i++) {
int maxx = -99999;
for (int j=E-1; j<i; j++) {
if (dp[j][E-1] + Math.abs(numbers[i] - numbers[j]) > maxx) {
maxx = dp[j][E-1] + Math.abs(numbers[i] - numbers[j]);
}
}
if(E < K && E-1>=0) {
dp[i][E-1] = maxx;
E++;
}
}
int maks = -9999;
for (int i=0; i<N; i++) {
if (dp[i][K-1] > maks)
maks = dp[i][K-1];
}
return maks;
}
public static void main(String[] args) throws Exception {
int i,j,k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int numbers[] = new int[N];
st = new StringTokenizer(br.readLine());
for (i=0;i<N;i++) {
numbers[i] = Integer.parseInt(st.nextToken());
}
int res = solve(numbers, N, K);
System.out.println(res);
br.close();
}
}
For example this test case:
10 3 1 9 2 3 6 1 3 2 1 3
My code gives 0, it should be 16.