zoukankan      html  css  js  c++  java
  • 课堂练习——返回一个整数数组中最大子数组的和

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

     

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

    二、源代码:

    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,缩小了我的查找范围。

  • 相关阅读:
    Python pip 下载速度慢? Windows 设置 国内源,用阿里云国内镜像加速
    Go timer 是如何被调度的?
    Go sync.Pool 浅析
    一次错误使用 go-cache 导致出现的线上问题
    golang面向对象分析
    一文完全掌握 Go math/rand
    这一次,彻底搞懂 Go Cond
    面试题:让你捉摸不透的 Go reslice
    当 Go struct 遇上 Mutex
    这可能是最容易理解的 Go Mutex 源码剖析
  • 原文地址:https://www.cnblogs.com/fychen0302/p/7008913.html
Copyright © 2011-2022 走看看