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

要求:

• 要求程序必须能处理1000 个元素;

• 每个元素是int32 类型的,出现子数组之和大于整型表示的最大范围会出现什么情况;

• 输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。

• 要求时间复杂度为O(n)。

程序源代码:

 1 public class Main {
 2     public static void main(String[] args){
 3         int numberLength = 10000000;
 4         int a[] = new int[numberLength];
 5         for(int i = 0;i < numberLength;i++){
 6             a[i] = (int)(Math.random() * 20 - 10);   // 产生的随机数范围在-9 ~ 9
 7         }
 8         System.out.print("产生的随机数的值为:");
 9         for(int i = 0;i < numberLength;i++){
10             System.out.print(a[i] + " ");
11         }
12         System.out.print("
");
13         int sum = a[0],s_temp = a[0];
14         for(int i = 1 ;i < numberLength;i++){
15             s_temp = s_temp + a[i];
16             if(s_temp < a[i]){
17                 s_temp = a[i];
18                 }
19             if(s_temp > sum){
20                 sum = s_temp;
21             }
22         }
23         
24         System.out.println("最大子数组的和为:" + sum);    
25     }

结果:当子数组的和超过int32所能表示的最大值时,将会输出负数。

原因:整数在内存中是以补码的形式存储的,最高位是负号位,0表示整数,1表示负数。当超过最大值时,开始向最高位进位,则整数最终以负数的形式表示出来。

注:Int32所能表示的数不超过231 - 1= 2147483647。

原文地址:https://www.cnblogs.com/jj352095583/p/4383529.html