r/competitivprogramming • u/aaru2601 • May 11 '20
codeforces problem
https://codeforces.com/contest/289/problem/B
How to do this using dp
3
Upvotes
1
r/competitivprogramming • u/aaru2601 • May 11 '20
https://codeforces.com/contest/289/problem/B
How to do this using dp
1
2
u/cluelessExplorer May 11 '20 edited May 11 '20
Hi, Previously posted without coding and posted a wrong solution (hence deleted my comment). Now coded and got my solution accepted.
These are the basic observations.
There is no need for a 2-d array. we can just use 1-d array.
every element in and array when substracted with other elements should be multiple of d. (a[1]-a[n] %d == 0)
if it doesn't satisfy the case 2 then you should return -1
if it satisfies case 2 then sort the array and find the values of middle position(s)
now it is just the case of iterating through the array and doing
int temp = (a[i] - a[mid])/d;count1 = count1 + Math.abs(temp);
note that if n*m is even then there will be 2 mid values. you need to count for both these values and your ans will be min of those two countsHope this helps.
Happy coding :)
Edit : Sorry didn't see we need to use DP. my solution is without using DP
Edit1 : Please do not consider point 6. should work with any of the middle values