I have an array and a long type variable called total that stands for it's sum.
If the array is of length n then the summation of it should be done like this:
sum = arr[0] + arr[n-1] + arr[1] + arr[n-2] +... until sum >= total and I have to print a string of the elements in the sum
My Approach :
I have executed loop till n/2 if n is even or n/2 + 1 if n is odd.
I am doing something like this :
String s = "";
if (n % 2 ==0)
loop = n/2;
else
loop = n/2 + 1;
for(int i=0 ; i < loop ; i++){
sum += arr[i];
s += arr[i] + " ";
if(check(sum , total)==true) break; //this function checks if sum>=total.
sum += arr[n];
s += arr[n] + " ";
if(check(sum , total)==true) break;
n--;
}
System.out.println(s);
Example : arr[ ]={10 , 20 , 30, 40, 50} and total = 120 then output should be :
10 50 20 40
my approach stills gives TLE in some test cases. I need more optimized solution than this. Help me here.
checkbreaking the looping? Is it throwing an exception?checkshoudl be within anif