Here is the code of my approach:
int max(int A, int B, int C)
{
return Math.Max(A, Math.Max(B,C));
}
void Main()
{
var e = new byte[] {5,6,1,4,9,3,1,2};
var i=0;
var j = e.Length-1;
int A = e[i];
int C = e[j];
int B = 0;
for(int x = i+1 ; x < j; x++) B+=e[x];
var mp = int.MaxValue;
var m = max(A,B,C);
Console.WriteLine("A={0} B={1} C={2}", A, B, C);
while(m < mp)
{
int AL = A+e[i+1];
int CR = C+e[j-1];
int BL = B-e[i+1];
int BR = B-e[j-1];
if(max(AL,BL,C) < max(A,BR,CR) )
{
A=AL;
B=BL;
i++;
}
else
{
C=CR;
B=BR;
j--;
}
mp = m;
m = max(A,B,C);
Console.WriteLine("A={0} B={1} C={2} MAX={3}", A, B, C, m);
}
Console.WriteLine(mp);
}
Yes, it is C#, but quite easy to trasscribe it in C/C++, as it is not using any .NET specific. With the sample input you have given, it is terminating in 6 steps:
A=5 B=24 C=2
A=11 B=18 C=2 MAX=18
A=11 B=17 C=3 MAX=17
A=11 B=14 C=6 MAX=14
A=12 B=13 C=6 MAX=13
A=12 B=4 C=15 MAX=15
13
Check here:
https://dotnetfiddle.net/LC92ZU[
^]
Same thing in C :(
#include <stdio.h>
#include <limits.h>
#define max(A,B,C) A > (B > C ? B : C) ? A : (B > C ? B : C)
#define N 10
int main()
{
int e[N] = {1, 1, 8, 1, 1, 3, 4, 9, 5, 2 };
int i=0;
int j = N-1;
int A = e[i];
int C = e[j];
int B = 0;
int x, AL, CR, BL, BR, m, mp = INT_MAX, L, R;
for(x = i+1 ; x < j; x++) B+=e[x];
m = max(A,B,C);
printf("A=%d B=%d C=%d\n", A, B, C);
while(m < mp)
{
AL = A+e[i+1];
CR = C+e[j-1];
BL = B-e[i+1];
BR = B-e[j-1];
L = max(AL,BL,C);
R = max(A,BR,CR);
if(L<R)
{
A=AL;
B=BL;
i++;
}
else
{
C=CR;
B=BR;
j--;
}
mp = m;
m = max(A,B,C);
printf("A=%d B=%d C=%d MAX=%d\n", A, B, C, m);
}
printf("%d", mp);
return 0;
}
Online:
http://ideone.com/v1NFTw[
^]