Last active
April 5, 2019 09:53
-
-
Save jinahya/d474a5d004e98d4cd191145e70169942 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.util.concurrent.ThreadLocalRandom.current; | |
/** | |
* A program finds the largest sum of contiguous subarrays. | |
* | |
* @see <a href="https://en.wikipedia.org/wiki/Maximum_subarray_problem#Kadane's_algorithm">Kadane's algorithm</a> | |
*/ | |
class Kadane2 { | |
static long kadane(final int[] A) { | |
if (A == null) { | |
throw new NullPointerException("A is null"); | |
} | |
long msf = 0; | |
long meh = 0; | |
System.out.printf("%1$4s %2$11s %3$11s %4$11s\n", "i", "A[i]", "meh", "msf"); | |
System.out.println("----------------------------------------"); | |
for (int i = 0; i < A.length; i++) { | |
meh = Math.max(meh, meh + A[i]); | |
msf = Math.max(msf, meh); | |
System.out.printf("%1$4d %2$11d %3$11d %4$11d\n", i, A[i], meh, msf); | |
} | |
System.out.println("----------------------------------------"); | |
return msf; | |
} | |
public static void main(final String... args) { | |
final int[] A; | |
if (args.length > 0) { | |
A = new int["empty".equals(args[0]) ? 0 : args.length]; | |
if (A.length > 0) { | |
for (int i = 0; i < A.length; i++) { | |
A[i] = Integer.parseInt(args[i]); | |
} | |
} | |
} else { | |
A = new int[current().nextInt(0, 16)]; | |
for (int i = 0; i < A.length; i++) { | |
A[i] = current().nextInt(-5, 5); | |
} | |
} | |
System.out.printf("%1$40d\n", kadane(A)); | |
} | |
/** | |
* Creates a new instance. | |
*/ | |
private Kadane2() { | |
super(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment