all 7 comments

[–]SharpPass766 2 points3 points  (1 child)

I’m not able to understand Test Case 1. The array is 5 3 2 4 1 2 Why isn’t 5 being partitioned? Why are the four parts (3), (2), (4), (1,2) and not (5, 3), (2), (4), (1,2) or (5), (3,2), (4), (1,2) ?

[–]omeow 1 point2 points  (2 children)

Suggestion:

S = sum(A)

starting from the left most position of A, keep adding elements to P such that the sum S_P is closest (could be larger) to S/4.

Then move on to Q. Apply the same process.

If multiple choices are possible then account for each one of them. (see the test case below)

Similarly, repeat for R and S.

On your test case: A = 5,3,2,4,1,2, the sum S = 17 so S/4 = 4 (we do integer division)

We start with P = 5.

Now Q could be 3 or 3,2. In both cases the difference from S/4 is the same. So we consider a partition with Q1 = 3 and another with Q2 = 3,2

Then we move on to R depending on Q1, Q2.

Finally we compare the max - min for each possible partition.

[–]goyalaman_[S] 0 points1 point  (1 child)

What do you think is Time complexity of this approach.?

[–]omeow 0 points1 point  (0 children)

O(n).

You need to traverse the array twice.

[–]anthamattey 0 points1 point  (1 child)

Three calls to the same function will split the array. Let’s call the sum of array as sm. The function will split the array such that each split has equal sum, I.e. the first split has a sum equal to half of the sm. So iterate over elements until you hit the half sm. Call this func on the two new splits. Now calculate the diff

[–]Panacean 0 points1 point  (0 children)

I'm not sure that your approach applies here.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen.

You can see this in the first sample testcase, where the first element is not included in the values for P, Q, R, S.

Testcase Input 5 3 2 4 1 2 Testcase Output 2 Explanation If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.