最大连续子数组之和(编程练习)
数组中最大的连续子数组之和,要求:
输入:一个数组
输出:这个数组中最大子数组和
测试用例:
输入 | 输出 |
[-1, 2, 3, 4] | 5 |
[-1, 2, -5, 3, -4] | 3 |
[-1, 20, -5, 30, -4] | 45 |
[-2, -3, -5, -1, -9] | -1 |
我的简陋代码如下:(使用遗忘了许久的JAVA编写)
1 package max_shuzu; 2 import java.util.*; 3 public class max_shu { 4 public static int max(int arr[], int n){ 5 int max = arr[0], cur = 0; 6 for(int i=0;i<n;i++){ 7 if(cur<0){ 8 cur = arr[i]; 9 }else{ 10 cur += arr[i]; 11 } 12 if(cur >= max){ 13 max = cur; 14 } 15 } 16 return max; 17 } 18 public static int arr1[] = {-1,2,3,-4};//test-eg 19 public static int arr2[] = {-1,2,-5,3,-4};//test-eg 20 public static int arr3[] = {-1,20,-5,30,-4};//test-eg 21 public static int arr4[] = {-2,-3,-5,-1,-9};//test-eg 22 public static void main(String args[]){ 23 System.out.println("eg:[-1,2,3,-4]\t\t\t"+max_shu.max(arr1,4));//test-result 24 System.out.println("eg:[-1,2,-5,3,-4]\t\t"+max_shu.max(arr2,4));//test-result 25 System.out.println("eg:[-1,20,-5,30,-4]\t\t"+max_shu.max(arr3,4));//test-result 26 System.out.println("eg:[-2,-3,-5,-1,-9]\t\t"+max_shu.max(arr4,4));//test-result 27 28 System.out.print("请输入元素的个数:"); 29 Scanner reader = new Scanner(System.in); 30 int num = reader.nextInt(); 31 Scanner arrinput = new Scanner(System.in); 32 int []arr = new int[num]; 33 for(int i=0; i<arr.length; i++){ 34 System.out.print("请输入数组的第"+(i+1)+"个元素:"); 35 arr[i] = arrinput.nextInt(); 36 } 37 System.out.println("最大子数组的和为:"+max_shu.max(arr,num)); 38 arrinput.close(); 39 reader.close(); 40 } 41 }
运行效果如下:
难点:
1. 相关算法
2. Java如何输入数组