Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could read all values into the array, and then start summing over the array. </p> <p>While reading the array, you would still need that much memory, but after reading, it would be free for other purposes.</p> <p>The structure of your code would benefit, imho, because now you could use a different source for your numbers - for example util.Random, and still search the array for the biggest sum, or search the same array for different sequence lengths, without rereading the input.</p> <p>BTW: I had a hard time reading the code, because:</p> <ul> <li>value/values/sumValues/nb_values - (why not maximumValues)? - all variables are values so this doesn't help understanding. </li> <li>loops are normally indexed wiht i and j or n. Value is misleading</li> <li>length_sequence is misleading too. sequence length is meant, but everybody would just use 'length', since there is no abiguity to other lengths.</li> <li>You use long names for trivial things, but a cryptic abbrevation for a not so trivial one. I read your problem-description and code, and don't know what your code does: What do you have meant by nb_values. Non-Blocking? Null-Byte? Nearby? What is it? </li> </ul> <p>My first impression was, that for a sequence of Ints: </p> <pre><code>3 9 2 4 6 4 3 2 4 4 5 6 9 3 2 1 9 9 9 </code></pre> <p>you would search for a sequence of length 3 up to the 9th value (not counting 3 and 9 itselfs) and search for the maximum (2+4+6), (4+6+4), ... (4+4+5), but the result is 34. You add the first 9 values. </p> <p>Suggestion: </p> <pre><code>import java.util.Scanner; class MaxChunk { int chunksize; public int[] readValues () { Scanner sc = new Scanner (System.in); chunksize = sc.nextInt (); int length = sc.nextInt (); int values[] = new int [length]; for (int i = 0; i &lt; length; i++) { values[i] = sc.nextInt(); } return values; } public int calc (int values[]) { int sum = 0; for (int i = 0; i &lt; chunksize; i++) { sum += values[i]; } int maximum = sum; for (int j = chunksize; j &lt; values.length; j++) { sum -= values [j - chunksize]; sum += values [j]; if (maximum &lt; sum) maximum = sum; } return maximum; } public static void main (String[] args) { MaxChunk maxChunk = new MaxChunk (); int values[] = maxChunk.readValues (); System.out.println (maxChunk.calc (values)); } } echo "3 9 2 4 6 4 3 2 4 4 5 6 9 3 2 1 9 9" | java MaxChunk </code></pre> <p>Yields 14. </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