DELISH - Editorial

Problem Link:

Practice
Contest

Difficulty:

Simple

Pre-requisites:

Dynamic Programming

Problem:

Given an array D[1…N], find max(abs((D[i] + … + 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[i] + … + 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[i], D[i] + 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[i], D[i] + HardLeftMax(i-1)) : similarly.
HardRightMin(i) = min(D[i], D[i] + HardRightMin(i+1)) : similarly.
HardRightMax(i) = max(D[i], D[i] + 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

20 Likes

@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 !

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”.

2 Likes

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.

10 Likes

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

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:
![][1]
[1]: http://discuss.codechef.com/upfiles/Screenshot_from_2013-06-17_21:52:15.png

5 Likes

same story… here :-/

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…

1 Like

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:

4 Likes

Well, @devanshug, you’re right and it is indeed a lot better now than it was before… I even got to write some Simple problems as a setter and I actually think I managed to write good tutorials here on forums… But sometimes I feel that this is all I got… Maybe it’s the lack of time that makes me think this way, but it’s still very frustrating and demotivating… I think I will try to work as hard as university allows me, in order to get a little bit better though :slight_smile: Thanks for your words

1 Like

dafaq is this code !!!whre’s a main() ??

1 Like

@kuruma, Being relatively new to competitive programming and algorithms besides the constraints due to university, i feel the same as i have not been able to solve more than 3 problems but each time we get stuck we learn something new(be it the simplest of things) but that is what should drive us as these little things go a long way in enhancing our programming skills. Bit by Bit, Bytes of knowledge can be acquired, learnt and applied to improve our speed and efficiency in solving more problems. And considering that you are a lot better than before, its an achievement in itself. Chin up!

2 Likes

@spandanpathak, It has a main… but nothing else is understandable. Probably we first need to replace all those variable to simple ones and the format it to understand where the functions start and end… :stuck_out_tongue:

That code gives me urges that he must have done something which he is hiding behind that dirty code :slight_smile:

1 Like

@shashank_jain: I always prefer akash4983’s code for this purpose . least use of templates , least use of all the big constructs and more of a simple oriented approach devoid of problems associated with using abs , fabs , mods etc.

It’s natural to feel this way maybe you were trying too hard…but as @devanshug said compare your knowledge now with what you have when you started…Key is to keep practicing…and C’mon you are the one who wrote questions like FCBARCA and CLBMSTRS which I loved to solve…these are way too creative…simple series questions hidden behind very creatively created stories…AWESOME MAN AWESOME!!! Happy Coding:-)

2 Likes

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:

1 Like

The code seems to be the output of a decompiler or obfuscator. Some reasons which come to my mind are either he would have done it to optimise the code (eg, compile with gcc -O3 and then decompile) or maybe he cheated from someone else so to make the code look different obfuscated it.

1 Like

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\n",x)

vector<LL> max_sum_left(int N, vector<LL> arr)
{
	vector<LL> res(N);
	for(int i = 0; i < N; i++)
	{
		res[i] = 0;
	}
	res[0] = arr[0];
	LL currMax = arr[0];
	for(int i = 1; i < N; i++)
	{
		currMax = max(arr[i],arr[i]+currMax);
		res[i] = 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[i] = 0;
	}
	res[0] = arr[0];
	LL currMin = arr[0];
	for(int i = 1; i < N; i++)
	{
		currMin = min(arr[i],arr[i]+currMin);
		res[i] = 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[i] = 0;
	}
	res[N-1] = arr[N-1];
	LL currMax = arr[N-1];
	for(int i = N-2; i >= 0; i--)
	{
		currMax = max(arr[i],arr[i]+currMax);
		res[i] = 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[i] = 0;
	}
	res[N-1] = arr[N-1];
	LL currMin = arr[N-1];
	for(int i = N-2; i >= 0; i--)
	{
		currMin = min(arr[i],arr[i]+currMin);
		res[i] = 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[i]-rightMin[i+1];
		if(diff >= maxDiffAbs)
			maxDiffAbs = diff;
		
		diff = rightMax[i+1]-leftMin[i];
		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

9 Likes

Nice work, I’ve also seen some of your tutorials and one time you even explained a problem to me. You have really nice logic, I think if you don’t give up you’ll become a really strong competitor and be able to fight for the first spots. Also, I’ve seen you complain a lot about math basis but you shouldn’t let it stop you from solving problems. If you do that you’ll just be wasting your talent, we should turn our weaknesses into our greatest strengths. In no way I’m saying this to only encourage you, I say this because it’s true.

4 Likes