[Solved] Optimization of java code for reducing complexity [closed]


The big O complexity of the algorithm is O(N) where N is the array size. You cannot improve on that … for the arguments provided and producing the same output.

There are some things that can be done to improve efficiency though.

  • Hint: look for a computation that is performed on each loop iteration that could be performed once.
  • Hint: look for some unnecessary object creation1
  • Hint: unnecessary use of a reference type.

There are one or two other questionable micro-optimizations, but see if you can spot them without any hints. (I say “questionable” because I suspect that the JIT compiler would do the same optimization itself.)

One final note: the actual speed of the code will be dominated by the print statement, and its ability of the OS to write stuff to (for example) the console. And probably by JVM startup / warmup effects … unless the fnc method is called many times.


1 – Notwithstanding anything else, new Integer(...) is the wrong way to convert an int to an Integer.

21

solved Optimization of java code for reducing complexity [closed]