zoukankan      html  css  js  c++  java
  • 返回一个整数数组最大子数组的和

    第一种算法(很麻烦)

    设计思想:

    1.通过随机数产生十个数。

    2.声明一些变量,包括:

    flag —— 用来控制子数组的长度,从一到十递增。

    sum —— 记录最大子数组的和,初始值为a[0]。

    s_temp —— 记录不断更新的子数组的和。

    3.通过一个while语句和两个for循环实现。需注意第二个for循环中,为防止数组越界,使用Math.min方法。

    源代码:

    		int a[] = new int[10];
    		for(int i = 0;i < 10;i++){
    			a[i] = (int)(Math.random() * 20 - 10);   // 产生的随机数范围在-9 ~ 9
    		}
    		System.out.print("产生的随机数的值为:");
    		for(int i = 0;i <10;i++){
    			System.out.print(a[i] + " ");
    		}
    		System.out.print("
    ");
    		
    		int sum = a[0],s_temp = 0,flag = 1;
    		while(flag < 10){
    			for(int j = 0;j < 10;j++){
    				s_temp = 0;
    				for(int k = j;k < Math.min(j+flag,10);k++){
    					s_temp = s_temp + a[k];
    				}
    				if(s_temp > sum){
    					sum = s_temp;
    				}
    			}
    			flag++;
    		}
    
    		System.out.println("最大子数组的和为:" + sum);
    		
    	}
    

      

    运行结果:

    第二种方法:

    设计思想:

    当我们加上一个正数时,和会增加;当我们加上一个负数时,和会减少。所以,当接下来的和使现在的和更小时,抛弃它。当目前的和大于最大值,更新最大值。

    源代码:

     1         int a[] = new int[10];
     2         for(int i = 0;i < 10;i++){
     3             a[i] = (int)(Math.random() * 20 - 10);   // 产生的随机数范围在-9 ~ 9
     4         }
     5         System.out.print("产生的随机数的值为:");
     6         for(int i = 0;i <10;i++){
     7             System.out.print(a[i] + " ");
     8         }
     9         System.out.print("
    ");
    10         int sum = a[0],s_temp = a[0];
    11         for(int i = 1 ;i < 10;i++){
    12             s_temp = s_temp + a[i];
    13             if(s_temp < a[i]){
    14                 s_temp = a[i];16             }
    17             if(s_temp > sum){
    18                 sum = s_temp;21             }
    22         }
    23         
    24         System.out.println("最大子数组的和为:" + sum);
  • 相关阅读:
    NO.05--谈一谈Angular 和 Vue.js 的对比。
    NO.04--我的使用心得之使用vue绑定class名
    No.03---Vue学习之路之模块化组织
    NO.02---聊聊Vue提升
    NO.01---今天聊聊Vuex的简单入门
    hello word!------为什么开通博客以及自我介绍
    JavaScript 常用正则示例
    Newtonsoft.Json(Json.Net)学习笔记
    aspx后台传递Json到前台的两种接收方法
    MVC5中后台提供Json,前台处理Json,绑定给Dropdownlist的例子
  • 原文地址:https://www.cnblogs.com/jj352095583/p/4363841.html
Copyright © 2011-2022 走看看