Created
March 11, 2020 15:31
-
-
Save lukec11/e2e63c949aa79e6816ef660b7620a7ca to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* @author Harshith Iyer (@harbar20) | |
* @author Luke Carapezza (@lukec11) | |
* @ver 0.1 | |
*/ | |
import java.util.Arrays; | |
import java.util.Random; | |
class MaxSequenceSum { | |
public static int sum(int[] ints) { | |
int sum = 0; | |
for (int num : ints) | |
sum += num; | |
return sum; | |
} | |
/** | |
* @param int[] ints - An unsorted array of integers | |
* The time complexity of this algorithm is O(4n^2) | |
* @return highest sum of a subsequence of the array | |
*/ | |
public static int maxSequenceSum(int[] ints) { | |
int max = 0; | |
for (int i = 0; i < ints.length; i++) { | |
for (int j = 0; j < i; j++) { | |
int[] subarray = Arrays.copyOfRange(ints, j, i); | |
int sum = sum(subarray); | |
if (sum > max) { | |
max = sum; | |
} | |
} | |
} | |
return max; | |
} | |
/** | |
* @param int size - the size of the reqested random int array | |
* @return an array of $size random ints | |
* generates and returns an array of $size random integers | |
*/ | |
public static int[] getRandomNumbers(int size) { | |
Random random = new Random(); | |
int[] randomNums = new int[20]; | |
for (int i = 0; i < 20; i++) { | |
randomNums[i] = random.nextInt(20) -10; | |
} | |
System.out.print("Array: "); | |
for (int i = 0; i < randomNums.length; i++) { | |
System.out.print(randomNums[i] + " | "); | |
} | |
return randomNums; | |
} | |
public static void main(final String[] args) { | |
final int[] ints = getRandomNumbers(20); | |
final int MAXSUM = maxSequenceSum(ints); | |
System.out.println("\nMax sum is: " + MAXSUM); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment