Hi, I have this homework assignment:
Let Pi be the element of arr in index i. We say an index i is ‘well-placed’ if there exists an index j (j >= i) so that summing the elements in Pi Pi+1 … Pj yields the index i. In other words, an index is ‘well-placed’ if a sequence of elements beginning at that index yields the index when summed.
We define ‘well-placed length’ of a well-placed index to be j-i+1 – The length of the sequence that when summed shows that the index is well placed. It is possible an index is well-placed with more than a single sequence of elements. The ‘well-placed length’ in that case is the maximal length of the various sequences defining the index as ‘well-placed’. The ‘maximal well-placed length’ is the maximum between the well-placement length of all well-placed indices in arr.
If no index in the array is well-placed, the maximal well-placed length is considered to be zero.
This is the code I wrote (that does not work):
int longestIndexHelper(int arr[], int i, int cur, int sum, int flag)
{
if((arr[i]==115)||(i<0))
return 0;
if((sum==0)&&(flag==0))
cur= i;
if((sum+arr[i]==cur)&&(arr[i]<=cur))
return longestIndexHelper(arr, i+1, i, sum+arr[i], 1)+1;
else return 0;
}
int longestIndex(int arr[], int length)
{
int l, h;
if(length<=0)
return 0;
l= longestIndexHelper(arr, length-1, 0, 0, 0);
h= longestIndexHelper(arr, length, 0, 0, 0);
if(h>=l)
return longestIndex(arr, length-1);
else
return longestIndex(arr, length-2);
}
I tried to understand why it doesn't return the maximal value, I assume that the IF and ELSE need to define something else to do... I'm allowed only to use these two functions. thank you!