recursive sub length - the longest series possible of ascending integers - c

I'm trying to write a recursive function that receives an array and it's size and some other variables (of my choice). The function returns the length of the longest series possible of ascending integers in the array. The limitation is not using loops and not calling other functions or using pointers or other libraries.
This is the code I wrote, which unfortunately isn't working and I don't understand why!
length4 = max_set(arr4, size4, 1, 0, 1, 1, 0);
int max_set(int arr[], int size, int max, int index1, int index2, int
currentMax, int i) {
int path1, path2;
if (index1 == size)
return currentMax;
if (index2 == size){
if (currentMax < max)
currentMax = max;
index1 = i + 1;
index2 = index1 + 1;
max = 1;
}
if (arr[index2]> arr[index1]){
path1 = max_set(arr, size, max + 1, index1, index2 + 1, currentMax, i);
path2 = max_set(arr, size, max + 1, index1 + 1, index2 + 1, currentMax, i);
}
path1 = max_set(arr, size, max, index1, index2 + 1, currentMax, i);
path2 = max_set(arr, size, max, index1 + 1, index2 + 1, currentMax,i);
if (path1 > path2)
return path1;
else
return path2;
}
Thank you!

I found the original code more complicated than it needs to be for the task at hand, so rather than try and fix it, I just simplified it:
#include <stdio.h>
#include <stdlib.h>
/*
* Determine maximum ascending sequence length using length so far.
* #arr points to first element of array.
* #size is length of array.
* #pos is position of remaining entries in array.
* #maxval is the maximum value included the sequence so far (if len > 0).
* #len is sequence length so far.
*
* Returns maximum ascending sequence length.
*/
int max_set_recurse(int arr[], int size, int pos, int maxval, int len)
{
int path1, path2, newlen;
if (size <= pos) {
/* Nothing left, so return sequence length so far. */
return len;
}
/* Try skipping the first remaining entry. */
path1 = max_set_recurse(arr, size, pos + 1, maxval, len);
if (len && arr[pos] <= maxval) {
/* First remaining entry is no larger than maximum value. */
/* Try beginning sequence at first remaining entry. */
newlen = 0;
} else {
/* Try extending the sequence with first remaining entry. */
newlen = len + 1;
}
path2 = max_set_recurse(arr, size, pos + 1, arr[pos], newlen);
/* Return the longest ascending sequence length of the two we tried. */
return path2 > path1 ? path2 : path1;
}
/*
* Determine maximum ascending sequence length
* #arr points to entries.
* #size is number of entries.
*
* Returns maximum ascending sequence length.
*/
int max_set(int arr[], int size)
{
return max_set_recurse(arr, size, 0, 0, 0);
}
int main(int argc, char *argv[])
{
int arr[argc - 1];
int i;
for (i = 1; i < argc; i++) {
arr[i - 1] = atoi(argv[i]);
}
printf("Longest ascending sequence length = %d\n", max_set(arr, argc - 1));
return 0;
}
(EDITED to comply with "no pointers" rule as far as possible in C, i.e. no overt use of pointers, given that arrays are passed as pointers, and array indexing is actually pointer arithmetic and pointer dereferencing in disguise!)
The max_set_recurse function is called with the remaining portion of the array to be checked (from pos onwards), the maximum value in the partial maximum ascending sequence so far (if any), and the length of the partial maximum ascending sequence so far (possibly zero).
If the remaining portion of the array is empty (size <= pos), just return the length of the sequence so far.
Otherwise, we can determine two sequence lengths, one that excludes the first remaining entry in the array (arr[pos]), and one that includes it. The function will return the maximum of these two sequence lengths.
For the recursion path that excludes the first remaining entry in the array, the recursion call will skip the first remaining entry and pass through the previous maximum value and sequence length.
For the recursion path that includes the first remaining entry in the array, the recursion call will skip the first remaining entry, use the value of the first remaining entry as the maximum value, and set the sequence length as follows:
if the previous length is zero, or the first remaining entry is greater than the previous maximum value, use the previous sequence length plus one;
otherwise, use a sequence length of zero.
The demo program is called with a sequence of numbers on the command line. It will print the length of the longest ascending sequence that can be found by skipping or including each element.
Here are some example command lines and outputs. I have marked the input numbers that form part of the longest sequence in bold, although the program does not report which numbers are part of the longest ascending sequence:
./ascend 3 23 2 45 0 21 80
Longest ascending sequence length = 4
./ascend 10 3 5 23 2 45 0 21 80
Longest ascending sequence length = 5
./ascend 10 3 5 23 2 45 21 80 20 21 22 23
Longest ascending sequence length = 6

Related

How to divide an array of n length into k sub arrays that have approximately equal sizes (in C)?

I have an array of size n, and want to divide into k number of sub arrays, and each array must have approximately the same size. I have been thinking for a while and know that you must use two for loops, but I am having a hard time implementing these for loop.
What I've Tried:
//Lets call the original integer array with size n: arr
// n is the size of arr
// k is the number of subarrays wanted
int size_of_subArray = n/k;
int left_over = n%k; // When n is not divisible by k
int list_of_subArrays[k][size_of_subArray + 1];
//Lets call the original integer array with size n: arr
for(int i = 0; i < k; i++){
for(int j = 0; j < size_of_subArray; j++){
list_of_subArrays[i][j] = arr[j];
}
}
I am struggling with getting the correct indexes in the forloops.
Any Ideas?
I've refactored your code and annotated it.
The main points are:
When calculating the sub-array size, it must be rounded up
The index for arr needs to continue to increment from 0 (i.e. it is not reset to 0)
The following should work, but I didn't test it [please pardon the gratuitous style cleanup]:
// Lets call the original integer array with size n: arr
// n is the size of arr
// k is the number of subarrays wanted
// round up the size of the subarray
int subsize = (n + (k - 1)) / k;
int list_of_subArrays[k][subsize];
int arridx = 0;
int subno = 0;
// process all elements in original array
while (1) {
// get number of remaining elements to process in arr
int remain = n - arridx;
// stop when done
if (remain <= 0)
break;
// clip remaining count to amount per sub-array
if (remain > subsize)
remain = subsize;
// fill next sub-array
for (int subidx = 0; subidx < remain; ++subidx, ++arridx)
list_of_subArrays[subno][subidx] = arr[arridx];
// advance to next sub-array
++subno;
}
UPDATE:
Yes this divides the arrays into n subarrays, but it doesn't divide it evenly. Say there was an array of size 10, and wanted to divide it into 9 subarrays. Then 8 subarrays will have 1 of original array's element, but one subarray will need to have 2 elements.
Your original code had a few bugs [fixed in the above example]. Even if I were doing this for myself the above would have been the first step to get something working.
In your original question, you did say: "and each array must have approximately the same size". But, here, there is the physical size of the list sub-array [still a rounded up value].
But, I might have said something like "evenly distributed" or some such to further clarify your intent. That is, that you wanted the last sub-array/bucket to not be "short" [by a wide margin].
Given that, the code starts off somewhat the same, but needs a bit more sophistication. This is still a bit rough and might be optimized further:
#include <stdio.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) /**/
#endif
int arr[5000];
// Lets call the original integer array with size n: arr
// n is the size of arr
// k is the number of subarrays wanted
void
fnc2(int n,int k)
{
// round up the size of the subarray
int subsize = (n + (k - 1)) / k;
int list_of_subArrays[k][subsize];
dbgprt("n=%d k=%d subsize=%d\n",n,k,subsize);
int arridx = 0;
for (int subno = 0; subno < k; ++subno) {
// get remaining number of sub-arrays
int remsub = k - subno;
// get remaining number of elements
int remain = n - arridx;
// get maximum bucket size
int curcnt = subsize;
// get projected remaining size for using this bucket size
int curtot = remsub * curcnt;
// if we're too low, up it
if (curtot < remain)
++curcnt;
// if we're too high, lower it
if (curtot > remain)
--curcnt;
// each bucket must have at least one
if (curcnt < 1)
curcnt = 1;
// each bucket can have no more than the maximum
if (curcnt > subsize)
curcnt = subsize;
// last bucket is the remainder
if (curcnt > remain)
curcnt = remain;
dbgprt(" list[%d][%d] --> arr[%d] remain=%d\n",
subno,curcnt,arridx,remain);
// fill next sub-array
for (int subidx = 0; subidx < curcnt; ++subidx, ++arridx)
list_of_subArrays[subno][subidx] = arr[arridx];
}
dbgprt("\n");
}

Permutations in lexicographical order with not unique characters

I want to make function to output all possible permutations from input string, in lexicographical order.
I have the following code:
void permutations_print(char *permutations, int index, int length) {
if (index == length) {
printf("\"%s\"\n", permutations);
}
for (int i = index; i < length; i++) {
rotate(permutations, i, index);
permutations_to_array(permutations, index + 1, length);
rotate_back(permutations, index, i);
}
}
void rotate(char to_swap[], int i, int j) {
char temp = to_swap[i];
for (int k = i; k > j; k--) {
to_swap[k] = to_swap[k - 1];
}
to_swap[j] = temp;
}
void rotate_back(char to_swap[], int i, int j) {
char tmp = to_swap[i];
for (int k = i; k < j; k++) {
to_swap[k] = to_swap[k + 1];
}
to_swap[j] = tmp;
}
The input string permutations is permutations_print is sorted.
It works without any issues for permutations with just unique characters, but I need it to work also for character non-unique strings, any ideas how to tweak it / modify it / to work? I have to use recursion and should not use any kind of sorting and I should not store it in any array, just print. And I want to print all, even duplicates.
Warning: not a C programmer, so my code can definitely be improved.
You can do it iteratively with something like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void swap(char* array, int i, int j);
void reverse(char* array, int left, int right);
bool nextPermutation(char* array, int n);
int compareCharacters(const void * a, const void * b);
void printPermutations(char *permutations, int length);
int main() {
char myArray[] = "hey";
printPermutations(myArray, 3);
return 0;
}
void printPermutations(char *array, int length) {
qsort(array, length, sizeof(char), compareCharacters);
*(array + length) = '\0';
do {
printf("%s\n", array);
} while (nextPermutation(array, length));
}
int compareCharacters(const void * a, const void * b) {
return (*(char*)a - *(char*)b);
}
bool nextPermutation(char* array, int n) {
if (n <= 1) {
return false;
}
// Find index, swapIndex1, of rightmost number that has a number greater than it
int swapIndex1;
for (swapIndex1 = n - 2; swapIndex1 >= 0; --swapIndex1) {
if (array[swapIndex1] < array[swapIndex1 + 1]) {
break;
}
}
if (swapIndex1 == -1) {
return false;
}
// Find index, swapIndex2, of smallest number to the right of that and greater than it
int swapIndex2 = swapIndex1 + 1;
int minToRight = array[swapIndex2];
for (int i = swapIndex2 + 1; i < n; ++i) {
if (array[i] <= minToRight && array[i] > array[swapIndex1]) {
minToRight = array[i];
swapIndex2 = i;
}
}
// Swap values at swapIndex1 and swapIndex2
swap(array, swapIndex1, swapIndex2);
// Reverse values from swapIndex1+1 to n-1
reverse(array, swapIndex1 + 1, n - 1);
return true;
}
void swap(char* array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
void reverse(char* array, int left, int right) {
for (; left < right; ++left, --right) {
swap(array, left, right);
}
}
The algorithm is described here. See the comments section for an example/explanation, or see transcription below:
Let's pretend we're finding the next largest permutation of digits from 1-9.
For example, suppose we have: 123479865
We want to find the smallest number greater than 123479865 that can be obtained by rearranging the digits of 123479865.
What this means is that we have to make at least one digit bigger than it currently is. If we had our choice, we would want to make the rightmost digit bigger since that will result in the smallest change. If we were to make a left number bigger, it would result in a bigger change in value.
e.g.: 123479865 => 123479866 is a much smaller change than 123479865 => 223479865.
Therefore, we want to find the farthest digit to the right that we can make bigger. In order to make a digit bigger, we have to find another number bigger than it within our sequence and then swap the two.
Note: we cannot swap a number (e.g., 5) with a number to its left (e.g., 6), because then we would be decreasing the value of a digit to our left, which would make our overall number smaller. For example, if we swapped 5 with 6, we would get 123479856, which is smaller than 123479865. Thus, we always swap with a number to our right.
So let's go through 123479865, starting with the rightmost digit.
There is nothing bigger than 5 to the right of 5, so we can't make 5 bigger.
Now let's consider 6. There is nothing bigger than 6 to the right of 6, so we can't make 6 bigger.
Now let's consider 8. There is nothing bigger than 8 to the right of 8, so we can't make 8 bigger.
Now let's consider 9. There is nothing bigger than 9 to the right of 9, so we can't make 9 bigger.
Now let's consider 7. There are a few numbers to the right of 7 that are bigger than 7, namely: 9 and 8. Therefore, we can make 7 bigger. We want to make it bigger by the least amount, so we should swap it with the smallest value that is bigger than 7. In other words, we should swap 7 with 8. That gives us: 123489765.
The number 123489765 is bigger than 123479865, but we can actually make it smaller while maintaining that it's bigger than 123479865. We can do this because we now have infinite freedom to change any of the following digits: 123489765 (anything to the right of 8). Those numbers can be as small as possible because the 8 to their left ensures that the new number is always bigger.
The best way to make the digits 9765 smaller is to sort them in increasing order, giving us 5679. Sorting works because the leftmost place values contribute the most to the overall value. Therefore, we want the leftmost digits to be the smallest digits.
That leaves us with 123485679, which is our answer.
Note: we don't actually have to sort the numbers to the right of 8. We can actually reverse their order because we know that the numbers from the right side to 8 are in increasing order (because earlier, we stopped the first time we got to a number that was smaller than its previous number).

Find the Number of Pairs that are Repeated in a List

Given an arbitrary char[] find the number of character pairs in the string. So this would be 3:
aabbcc
If two pairs of the same character adjacent both pairs should be counted. So this would be 3:
aaaabb
An interrupting single char must reset the count of consecutive character pairs. So this would be 1:
aabcc
If the interrupting single char is the same as the preceding pair it does not reset the count of consecutive character pairs. So this would be 3:
aabbbccc
This is an adaptation from this question. The original interpretation of the question was interesting but the comments kept changing the nature of that question from it's original interpretation. This was my answer to that original interpretation, and I was wondering if improvement could be made upon it?
Loop control should use the size of the array for the range, and indexing of a[i + 1] may be out of bounds if i is the index to the last element, so using a[i - 1] instead and iterating over the range [1 .. sizeof(a) / sizeof(a[0])] is preferable
The algorithm is best solved with 3 variables:
char* last points to the first element of the current string of consecutive characters
int count1 the number of consecutive pairs in the current count
int count the highest number of recorded consecutive pairs
The algorithm is best illustrated with a state machine. It will operate on :
Upon entry set last to NULL, if count1 is larger than count assign count1 to count, and reset count1 to 0
Upon entry set last to the first character in this string of consecutive characters (a[i-1])
Upon entry add the number of consecutive characters pointed to by last divided by 2 so as to only find the pairs
This is corrected code with comments inline:
size_t i = 0;
char* last = NULL;
long int count1 = 0;
long int count = 0;
char a[] = {'d', 'p', 'p', 'c', 'c', 'd', 'd', 'd'};
while (++i < sizeof(a) / sizeof(a[0])) { // This will iterate over the range: [1 .. sizeof(a) / sizeof(a[0])]
if (a[i - 1] == a[i]) { // Test previous character to avoid going out of range
if (last == NULL) { // Entry to state 2
last = a + i - 1;
}
} else if (last != NULL) {
if (a + i - last > 1) { // Entry to state 3
count1 += (a + i - last) / 2;
last = a + i;
} else { // Entry to state 1
if (count1 > count) { // If the current count is larger
count = count1; // Replace the maximum count
}
count1 = 0; // Reset the current count
last = NULL;
}
}
}
if (last != NULL) { // Entry to state 3
if (a + (sizeof(a) / sizeof(a[0])) - last > 1) {
count1 += (a + (sizeof(a) / sizeof(a[0])) - last) / 2;
}
if (count1 > count) { // If the current count is larger
count = count1; // Replace the maximum count
}
}
printf("%ld", count);
[Live Example]

Finding the length of the longest ascending sub-series in an array using recursion and no loops

i've been stuck for hours trying to figure how can i write a function that gets and array of integers, and finds the length of the longest ascending sub-series in the array using recursion and no loops at all. im only allowed to use another 1 recursive function
for example, for the following array: {45,1,21,3,3,6,53,9,18} the outpot should be 5, because the longest sub-series is {1,3,6,9,18}.
So, basicly, a function that gets an array and its size, and needs to print the length of the longest sub-series using no loops at all, no global/static types, and it may use another "help" recursive function and thats it.
this is pretty much all i came up with, and its a mess and not working well.
I'm trying to scan the array while at all time i know the current index im looking at, the index that is being compared to the current, and the originla index from which i started the current sub-series.
I tried to scan the array while knowing the indexes that should be compared but i got stuck, here's what i got, i would really appreciate any tips and advices.
thanks.
void max_set(int arr[], int size)
{
int bigSeries[2] = { 0 };
calcSeries(arr, bigSeries,0, 0, 1, size -1, 1);
printf("number of max parts going up %d \n", bigSeries[0]);
}
void calcSeries(int arr[], int bigSeries[],int originalCHeckedIndex, int checkedIndex, int currentIndex, int lastIndex, int ascending)
{
if ((checkedIndex == lastIndex) || (currentIndex > lastIndex))
{
if (ascending > bigSeries[0])
bigSeries[0] = ascending;
if (originalCHeckedIndex == lastIndex)
return;
else
{
calcSeries(arr, bigSeries, originalCHeckedIndex + 1, originalCHeckedIndex + 1, originalCHeckedIndex + 2, lastIndex, 0);
return;
}
}
if (arr[currentIndex] > arr[checkedIndex])
{
calcSeries(arr, bigSeries, originalCHeckedIndex, currentIndex, currentIndex + 1, lastIndex, ascending + 1);
}
else
{
if (arr[originalCHeckedIndex] < arr[currentIndex])
calcSeries(arr, bigSeries, currentIndex, currentIndex, currentIndex + 1, lastIndex,ascending);
calcSeries(arr, bigSeries, originalCHeckedIndex, checkedIndex, currentIndex + 1, lastIndex, ascending);
}
}
The algorithm has many similarities with the one of first answer, yet covering a few corner cases you might want to watch out. Instead of writing a lengthy comment, I chose to write a new answer instead.
Sanity Checks
Do some sanity checks on the array, as I did in function max_set().
Is an array supplied at all (check for NULL)?
Is the supplied array size at least positive (consider size_t)?
Allowed Values
Data type int allows positive and negative values. The algorithm should handle both. At least I didn't read from your post that they have to be positive. My code looks a bit nicer if you skip that part.
Recursion
The idea of this algorithm (and the one from first answer) is to recursively walk through the array, beginning at the first element, ending at last. So this already defines the start and end of recursion, as documented in source code.
To find the longest sub-series of numbers this way, there are always three possibilities:
The longest sub-series can be reached by skipping the number that is currently processed
The longest sub-series can be reached by adding the number that is currently processed
The currently processed number cannot fit in
A number can be added if it's larger than the largest previously added number; we look for an ascending series after all. The current number could be larger than others in the array that have to be processed, yet. So we have to take both possibilities into account: continuing recursive steps without it and with it -- as long as it fits criteria.
Possible oversight
Take into account that INT_MIN, the smallest possible int value on the machine, is a perfectly valid number in the array. I have added the variable seen, which just records if INT_MIN has been seen at least once in the array or not. On first encounter, seen flips from 0 to 1, not allowing any further INT_MIN values due to requirement of ascending sub-series. Your example shows this requirement with two occurences of number 3.
Tests
Try to find various test cases, and think out of the box at times. NULL for array, negative size, empty array. Next, add fancy values like negative numbers, INT_MIN. Or create ascending series, descending ones, interlacing. Numbers occuring multiple times ...
#include <sys/limits.h>
#include <stdio.h>
int
analyze(int arr[], int size, int min, int seen)
{
int sub_count = 0, count = 0;
/* end of recursion */
if (size == 0)
return 0;
/* recursion step, without and with current number */
sub_count = analyze(arr + 1, size - 1, min, seen);
if (arr[0] > min || (min == INT_MIN && arr[0] == INT_MIN && !seen))
count = 1 + analyze(arr + 1, size - 1, arr[0], arr[0] == INT_MIN);
/* return length of largest sub-series */
return sub_count > count ? sub_count : count;
}
void
max_set(int arr[], int size)
{
int seq = 0;
if (arr != NULL && size > 0) {
/* start of recursion */
seq = analyze(arr, size, INT_MIN, 0);
}
printf("max sequence is %d\n", seq);
}
int
main(void)
{
int arr[] = { 45, 1, 21, 3, 3, 6, 53, 9, 18 };
max_set(arr, sizeof(arr) / sizeof(*arr));
return (0);
}
#include <stdio.h>
int calcSeries(int arr[], int size, int value, int count){
int self, skip, rest;
if(0 == size)
return count;
skip = calcSeries(arr + 1, size-1, value, count);//case of skip the top(self)
if(value < *arr){
self = calcSeries(arr + 1, size-1, *arr, count+1);//case of include top
if(skip > self)
self = skip;
} else
self = skip;
rest = calcSeries(arr + 1, size-1, -1, 0);
return self > rest ? self : rest;
}
void max_set(int arr[], int size){
printf("number of max parts going up %d \n", calcSeries(arr, size, -1, 0));
}
int main(void){
int array[]={45,1,21,3,3,6,53,9,18};
max_set(array, sizeof(array)/sizeof(*array));
return 0;
}

maximal value in recursion

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!
The problem seems to be that you need to implement two "loops" via recursion; one is a loop starting at a given index and summing the values as it goes, keeping track of the maximum well placed length for that starting index. The other is a loop trying each possible starting index. I see that your helper function does the former. It seems that you intend the called function to do the latter, but it has no mechanism to keep track of the maximum found so far or the index to check, separate from the length of the input array. To do that, you might want to create another helper function to recurse through all the possible starting indexes. Though I would approach this by expanding the existing helper function to do this also, something like:
int _helper( int arr[], int len, int start, int cur, int sum, int max )
{
if (start >= len) {
/* game over, thanks for playing */
return max;
} else if (cur >= len) {
/* try another starting index */
return _helper( arr, len, start + 1, start + 1, 0, max );
} else if ( sum + arr[cur] == start && max < cur - start + 1 ) {
/* found a longer well placed length */
return _helper( arr, len, start, cur + 1, sum + arr[cur], cur - start + 1 );
} else {
/* bzzzt. try a longer length at this starting index */
return _helper( arr, len, start, cur + 1, sum + arr[cur], max );
}
}
int max_well_placed_length( int arr[], int len )
{
return _helper( arr, len, 0, 0, 0, 0 );
}
#include <stdio.h>
int main(int argc, char **argv) {
int arr[100];
int len = 0;
if (argc > 100) return 1;
while (--argc) sscanf(*++argv, "%d", &arr[len++]);
printf("max well placed length: %d\n", max_well_placed_length(arr, len));
return 0;
}
Assume that your longestIndex function finds the 'maximal well-placed length' for a given length parameter. Then it drops it (h and l aren't stored or returned anywhere, are they?), and calls itself with a decreased length. So the function will always return the result of either longestIndex(arr, 0) or longestIndex(arr, -1) which will be always 0.
EDIT: and the longestIndexHelper function can return only 0 too.

Resources