DELISH - Editorial

delish
dynamic-programming
editorial
june13
simple

#1

Problem Link:

Practice
Contest

Difficulty:

Simple

Pre-requisites:

Dynamic Programming

Problem:

Given an array D[1…N], find max(abs((D* + … + D[j]) - (D[k] + … D[l])) : 1<= i <= j < k <= l <= N).

Explanation:

Let us look at the final solution, and work backwards. Let the final solution be due to some i0, j0, k0, l0. We now have two cases:

Case 1: D[k0] + … + D[l0] <= D[i0] + … + D[j0].
In this case, we get that among all possible choices of l, D[k0] + … + D[l] is MINIMUM for l = l0. Else, we could choose such l, and this would give us a larger absolute difference. We also get, that among all 1 <= i <= j <= k0-1, D* + … + D[j] is MAXIMUM.

Case 2: D[k0] + … + D[l0] > D[i0 + … + D[j0].
In this case, among all possible choices of l, we choose l0 to give the MAXIMUM value of the sum, and we choose i0, j0 to give the MINIMUM possible sum.

Hence, it would be useful precomputing values that answer “what is the [minimum|maximum] value I can get if I [start|end] at position i?”

Solution 1

The above setting motivates the following few definitions:
HardLeftMin(i) = Minimum value of the sum of a contiguous subarray whose rightmost point = i.
HardLeftMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point = i.
SoftLeftMin(i) = Minimum value of the sum of a contiguous subarray whose rightmost point <= i.
SoftLeftMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point <= i.
HardRightMin(i) = Minimum value of the sum of a contiguous subarray whose leftmost point = i.
HardRightMax(i) = Maximum value of the sum of a contiguous subarray whose rightmost point = i.

Recurrences for the above are easy to find:
HardLeftMin(i) = min(D*, D* + HardLeftMin(i-1)) : either you select position i-1 as well in your subarray and take the best from there, or you don’t even take position i-1.
HardLeftMax(i) = max(D*, D* + HardLeftMax(i-1)) : similarly.
HardRightMin(i) = min(D*, D* + HardRightMin(i+1)) : similarly.
HardRightMax(i) = max(D*, D* + HardRightMax(i+1)) : similarly.
SoftLeftMin(i) = min(HardLeftMin(i), SoftLeftMin(i-1)) : either your minimum ends at points i, or it ends at some point <= i-1.
SoftLeftMax(i) = max(HardLeftMax(i), SoftLeftMax(i-1)) : similarly.

Note that, using the above recurrences, we can calculate all the arrays in O(N) time using dynamic programming.

Finally, our case (1) will be covered by SoftLeftMax(j0) - HardRightMin(j0+1), and case (2) will be covered by HardRightMax(j0+1) - SoftLeftMin(j0).
Iterate over all values of j0, and take the maximum, as your answer. This again takes O(N) time to run.

Solution 2

This solution cleverly disposes of SoftLeftMin, SoftLeftMax() functions and works relying on the following claim.

Claim: Without loss of generality, k0 - j0 = 1. That is, we can consider our optimal phases as being consecutive.

Let us say that OPT returned i, j, k, l, with k-j > 1. Now, consider sum S = D[j+1] + D[j+2] + … + D[k-1]. If S >= 0, then it can be added to the larger of the two segments [i…j], [k…l]. If S <= 0, then the segment can be added to the smaller of the two segments [i…j], [k…l]. In both cases, it gives us a Delish value atleast as good as the Optimal. Hence, wlog, the two segments we choose are consecutive.

Thus, finally, we iterate over j, and consider abs(LeftMax(j) - RightMin(j+1)) and abs(RightMax(j+1) - LeftMin(j)) as candidates. This approach was used by the Setter.

Setter’s Solution:

Can be found here

Tester’s Solution:

Can be found here


#2

@pragrame - shouldn’t we also include abs(LeftMax(j)-RightMax(j+1)) and abs(LeftMin(j)-RightMin(j+1)) as well because we are considering abs value ? If LeftMin(j)=-2 and RightMax(j+1)=4 and RightMin(j+1)=-10, then the max. abs value among these is abs(LeftMin(j)-RightMin(j+1)) which is not checked! I apologise if I am missing some point ! Thanks !


#3

Can anyone explain me this solution of karlheinz_jung??? I have tried my best to understand it, but unfortunately I can’t.

Those who solved this question help me in figuring a case where my solution went wrong.


#4

As contests pass by… and as I see I keep struggling to solve only 3 maybe 4 problems over 10 days… The more convinced I get that I might be too dumb for doing Algorithms at the minimum acceptable competitive level… After reading editorial I believe I understood the underlying idea behind DP a bit better (Truth is, I say this, but, as I never, or rarely get the chance to practice properly, I always end up only reading the editorial and not coding anything with my own comments etc, etc, which is what I think is needed to gain more skill).

Nontheless, I found it absolutely hillarious that my code almost had the same designations as the Solution 2 described in editorial… However, I got stuck with the code EXACTLY like this for all the contest, after solving 3 problems in the 1st day of contest…

I can’t express how frustrated I feel with myself right now at this moment… I feel like FUCKTHISSHIT

I really hope I can improve something… If I can’t, this is just… very demotivating… :frowning:


#5

Can anyone pls tell where i am going wrong in this solution…
sol_1

I used the same approach… and got ACed when i did this :
sol_2

Thank you in advance !! :slight_smile:


#6

So, finally, after reading the editorials several times and after searching for some AC solutions, I finally got AC with my solution in C++:

/* Problem DELISH @Codechef JUN13 Long Contest
 * 
 * Main idea is to use DP approach to solve problem in linear time.
 * We need to maintain 4 vectors that will store:
 * - Max value of delish starting from left
 * - Max value of delish starting from right
 * - Min value of delish starting from left
 * - Min value of delish starting from right
 * 
 * Now, since the value of a partial sum is always either >= 0 or <=0
 * it is safe to assume that the optimal indexes i,j,k and l
 * which form the intervals to substract are in fact contigous.
 * This is because either we add a value to one of them and increase it
 * , or we add it to the other one which also increases it, towards the
 * first interval. This yields, wlog, the optimal answer. */
#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <stdio.h>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long int LL;
#define put(x)	printf("%lld",x)

vector<LL> max_sum_left(int N, vector<LL> arr)
{
	vector<LL> res(N);
	for(int i = 0; i < N; i++)
	{
		res* = 0;
	}
	res[0] = arr[0];
	LL currMax = arr[0];
	for(int i = 1; i < N; i++)
	{
		currMax = max(arr*,arr*+currMax);
		res* = max(res[i-1], currMax);
	}
	return res;
}

vector<LL> min_sum_left(int N, vector<LL> arr)
{
	vector<LL> res(N);
	for(int i = 0; i < N; i++)
	{
		res* = 0;
	}
	res[0] = arr[0];
	LL currMin = arr[0];
	for(int i = 1; i < N; i++)
	{
		currMin = min(arr*,arr*+currMin);
		res* = min(res[i-1], currMin);
	}
	return res;
}

vector<LL> max_sum_right(int N, vector<LL> arr)
{
	vector<LL> res(N);
	for(int i = 0; i < N; i++)
	{
		res* = 0;
	}
	res[N-1] = arr[N-1];
	LL currMax = arr[N-1];
	for(int i = N-2; i >= 0; i--)
	{
		currMax = max(arr*,arr*+currMax);
		res* = max(res[i+1], currMax);
	}
	return res;
}

vector<LL> min_sum_right(int N, vector<LL> arr)
{
	vector<LL> res(N);
	for(int i = 0; i < N; i++)
	{
		res* = 0;
	}
	res[N-1] = arr[N-1];
	LL currMin = arr[N-1];
	for(int i = N-2; i >= 0; i--)
	{
		currMin = min(arr*,arr*+currMin);
		res* = min(res[i+1], currMin);
	}
	return res;
}

LL compute(int N, vector<LL> arr)
{
	LL maxDiffAbs = arr[0]-arr[1];
	vector<LL> leftMax = max_sum_left(N,arr);
	vector<LL> leftMin = min_sum_left(N,arr);
	vector<LL> rightMax = max_sum_right(N,arr);
	vector<LL> rightMin = min_sum_right(N,arr);
	
	LL diff;
	for(int i = 0; i < N-1; i++)
	{
		diff = leftMax*-rightMin[i+1];
		if(diff >= maxDiffAbs)
			maxDiffAbs = diff;
		
		diff = rightMax[i+1]-leftMin*;
		if(diff >= maxDiffAbs)
			maxDiffAbs = diff;
	}
	return maxDiffAbs;
}

int main()
{
	int t,dim;
	scanf("%d",&t);
	for(int i = 0; i < t; i++)
	{
		scanf("%d",&dim);
		vector<LL> arr;
		for(int j = 0; j < dim; j++)
		{
			LL elem;
			scanf("%lld",&elem);
			arr.push_back(elem);
		}
		LL ans = compute(dim,arr);
		put(ans);
	}
		
	return 0;
}

Thanks for this enlightening editorial @pragrame, which allowed me to write what I believe to be a clean solution for this problem!

Keep the good work up :smiley:

I hope I can also devote some of my time to understand the problem W-string a bit better and hopefully code a solution for it as soon as my time allows me to do so!

I hope I can really improve something with this good contest :smiley:

Also, @xpertcoder, Thanks for your words! As you probably noticed, those problems are easy ones and those are the concepts which I can say that I feel most comfortable with, so, as you can see I still have a loong way to go :slight_smile:

Best regards,

Bruno


#7

I made 2 functions using Kadane’s algorithm for max and min.
Function max gave me i,j,sum1.
Function min gave me k,l,sum2.
I took four cases.
1)max(0,arr.length-2) and min(j+1,arr.length-1) result1=Math.abs(sum1-sum2).
2)min(0,arr.length-2) and max(l+1,arr.length-1) result2=Math.abs(sum1-sum2).
3)max(1,arr.length-1) and min(0,i-1) result3=Math.abs(sum1-sum2).
4)min(1,arr.length-1) and max(0,k-1) result4=Math.abs(sum1-sum2).
I took maximum of all four results.I satisfied all given cases as well as cases in comments still I got WA always any help or case where it fails please :frowning: :(…


#8

Cannot figure out what’s wrong…Please Help…
http://www.codechef.com/viewsolution/2279041


#9

@sid4art i did the same thing and got WA!
http://www.codechef.com/viewsolution/2276586

Can someone please point out what is wrong with this approach?


#10

http://www.codechef.com/viewsolution/2299047

Can anyone tell whats wrong in this code???


#11

By same reasoning , one can implement Kadane algorithm too.


#12

Can anyone explain me the output for
5
10 3 1 2 9

The output according to setter’s or tester’s code is 12. How?


#13

@dsahapersonal assuming t=1,n=5,d={10,3,1,2,9}, that is the correct answer ! We need to basically find two contiguous subarrays (no intersecting point) such that the absolute difference(if the diff is negative,it turns positive) between the sum of each subarray is maximum .Now,the main thing to note here is that the length of the subarray could also be 1. Therefore , if you consider these two subarrays : {10,3} and {1} then the difference is absolute(1-(10+3))=absolute(-12) = 12 ! Also if you take any other pair of subarrays ,you will find that the absolute difference is not greater than that.


#14

The sixth function is wrongly written. It should be leftmost not rightmost.

HardRightMax(i) = Maximum value of the sum of a contiguous subarray whose leftmost point = i.


#15

The above solution provided in tutorial is giving tle while submitting in the java and the same solution give ac while submitting in java why?
Java Solution->https://www.codechef.com/viewsolution/21872923
C++ Solution->https://www.codechef.com/viewsolution/21872897


#16

Not really. In your example, you say LeftMin(j) - RightMin(j+1) is larger. But note that LeftMin(j) <= LeftMax(j). So your case will be considered (and potentially bettered) in the check for LeftMax(j) - RightMin(j+1). You can check that the same will happen with comparing other pairs - wherever you compare difference of “max with max” or “min with min”.


#17

really… that annoying… coding right… it’s better to understand someother code(esp. above tutorial) than that purely written code…


#18

same story… here :-/


#19

haha… I knew it bro… I was jst thinking, in what world karlheinz would be, when he wrote the code… I mean how a person can write such a code… I think he himself cant xplain that…


#20

think it this way… Compare your present knowledge with the knowledge you had when you started competitive coding… we all know that it must be way better than at that time… Now you are a part of a dedicated community whose members are not only working for themselves but are working for each other… At least you are better than your mates who dont even knw a bit about competitive programming… At least we try our best to solve these tuff problems and become part of a big competitions… Cheerup bro these conditions will reoccur… all what we need is unstoppable efforts… :wink: