课堂练习——返回一个整数数组中最大子数组的和

返回一个整数数组中最大子数组的和

 

一、题目要求: 输入一个一维整形数组,数组里有正数也有负数。 一维数组首尾相接,像一条首尾相接的带子一样。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。求所有子数组的和的最大值。 

 

二、源代码:

package demo;  

 2   

 3 public class T1 {  

 4     public static int Max(int[] a) {  

 5         int []b=new int[10];

 6         int m = 0;

 7         int n = 0;  

 8         int i;

 9         int j=0;

10         int t=0;

11         for (i = 0; i < a.length; i ++) {  

12             n += a[i];  

13             if (n > m)           

14                 m = n;  

15             else if (n < 0)  

16                 n = 0;  

17         }  

18         int k=a[0];

19         for(i = 0;i < a.length;i ++) {            

20                if(k > a[i]) { 

21                  k = a[i]; 

22                  j = i; 

23                } 

24         }

25         t = j; 

26         i = 0; 

27         while(j < a.length) {        

28                 b[i] = a[j]; 

29                 i ++; 

30                 j ++;  

31         }    

32         j = 0; 

33         while(j < t) {          

34                b[i] = a[j];

35                i ++; 

36                j ++; 

37         } 

38         n = 0; 

39         for(i = 0;i < a.length;i ++) {          

40                n += b[i];

41                if(m < n) {  

42                   m = n; 

43                } 

44                if(n < 0) {               

45                    n = 0; 

46                } 

47         }

48         return m;

49  

50 } 

51 

52     public static void main(String[] args) {  

53         int a[] = { 6 , -5 , 1 , 4, 7, 10};  

54         System.out.println("最大子数组的和为"+Max(a));  

55     }  

56 }

 

三、合作过程

在此次代码编写过程中,我主要负责代码复审和代码测试,我是将各功能分步去实现的,这样有助于我找出代码中存在的bug,缩小了我的查找范围。

 

posted @ 2017-06-14 15:00  Chen啵啵  阅读(137)  评论(0编辑  收藏  举报