1 public class Maxsum { 2 public int maxsum(int[] array) { 3 if (array == null || array.length == 0) { 4 throw new IllegalArgumentException("array is null or empty."); 5 } 6 7 8 int result = array[0], mark = 0; 9 10 for (int i = 0; i < array.length; i++) { 11 int element = array[i]; 12 13 if (mark >= 0) { 14 mark += element; 15 } else { 16 mark = element; 17 } 18 19 if (mark > result) { 20 result = mark; 21 } 22 } 23 return result; 24 } 25 26 public static void main(String[] args) { 27 Maxsum maxsum = new Maxsum(); 28 int maxSum = maxsum.maxsum(new int[]{-2,2,-5,3,-4}); 29 System.out.println(maxSum); 30 }
时间: 2024-12-11 20:58:16