Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Get max sum from 2D array example
- * Use Kadane's algorithm
- * Maximum subarray problem: https://en.wikipedia.org/wiki/Maximum_subarray_problem
- * Author: https://github.com/InterVi
- */
- import java.lang.Math;
- import java.util.AbstractMap.SimpleEntry;
- import java.util.Map.Entry;
- public class MaxSumExample {
- public static void main(String[] args) { //testing
- int[][] test = {
- {-1, -2, -1},
- {-20},
- {-40, -50},
- {-1, 2, 3, -4, 5}, //6
- {4, -1, 2, 1}, //6, least summands, this will print
- {1, 1},
- {2, -4, -1},
- {1, 1}
- };
- System.out.print(maxSum2D(test, false));
- }
- /**
- * @return key - summands, value - result
- */
- public static Entry<Integer, Integer> maxSum(int[] a) {
- int result = a[0]; //get first value for correct comparison
- int sum = a[0];
- int items = 1; //summands
- for (int i = 1; i < a.length; i++) {
- sum = Math.max(sum + a[i], a[i]); //first step getting max sum, temporary value
- //result = Math.max(result, sum); //if no need summands
- if (sum > result) { //save current max sum
- result = sum;
- items++; //update summands
- }
- }
- return new SimpleEntry<>(items, result);
- }
- /**
- * @param array
- * @param useLength true - use length least value, false - use summands least value for get index
- * @return key - index in array with max sum, value - sum
- */
- public static Entry<Integer, Integer> maxSum2D(int array[][], boolean useLength){
- int lastIndex = 0; //index with max sum
- int lastMax = Integer.MIN_VALUE; //max sum
- int lastLength = 0; //last array[i].length or summands, for get index with the least value (length or summands)
- for (int i = 0; i < array.length; i++) {
- Entry<Integer, Integer> entry = maxSum(array[i]); //get sum and summands in subarray
- int newLength = useLength ? array[i].length : entry.getKey(); //use length or summands
- if (entry.getValue() == lastMax && newLength <= lastLength) { //save index with the least value (length or summands)
- lastIndex = i;
- } else if (entry.getValue() > lastMax) { //update index and max sum value
- lastIndex = i;
- lastMax = entry.getValue();
- }
- lastLength = newLength; //save length or summands for use next iteration
- }
- return new SimpleEntry<>(lastIndex, lastMax);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement