Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Smallest codesize I could get:</p> <pre><code>public class RecursiveTry { public static void main(String[] args) { int[] x = new int[] {1,2,4,3,3,32,100}; System.out.println(Max(x, 0)); } public static int Max(int[] arr, int currPos) { if (arr.length == 0) return -1; if (currPos == arr.length) return arr[0]; int len = Max (arr, currPos + 1); if (len &lt; arr[currPos]) return arr[currPos]; return len; } } </code></pre> <p>A few things:</p> <p>1/ If the array is zero-size, it returns a max of -1 (you could have another marker value, say, -MAX_INT, or throw an exception). I've made the assumption for code clarity here to assume all values are zero or more. Otherwise I would have peppered the code with all sorts of unnecessary stuff (in regards to answering the question).</p> <p>2/ Most recursions are 'cleaner' in my opinion if the terminating case is no-data rather than last-data, hence I return a value guaranteed to be less than or equal to the max when we've finished the array. Others may differ in their opinion but it wouldn't be the first or last time that they've been wrong :-).</p> <p>3/ The recursive call just gets the max of the rest of the list and compares it to the current element, returning the maximum of the two.</p> <p>4/ The 'ideal' solution would have been to pass a modified array on each recursive call so that you're only comparing the first element with the rest of the list, removing the need for currPos. But that would have been inefficient and would have bought down the wrath of SO.</p> <p>5/ This may not necessarily be the best solution. It may be that by gray matter has been compromised from too much use of LISP with its CAR, CDR and those interminable parentheses.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload