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

要求: 输入一个整形环状数组,数组里有正数也有负数。

数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

求所有子数组的和的最大值。要求时间复杂度为O(n)

思路:首先例如一个数组 -5 6 7 -10 -9

数组元素:                                          -5                         6                         7                           -10                         -9

从第二个开始                                      -5                  -5+6=1<6          6+7=13>7             13-10=3>-10     3-9=-6>-9

值所对应的子数组         -5                           6                       6  7      6 7 -10    6 7-10 -9

可以发现a[i-1]+a[i]的值和a[i]无非就两种关系,一个是大于,一个是小于,如果大于则子数组加上a[i-1],如果小于,则不加a[i-1],然后选出第二行中最大的值就可以了,环状要移动位置。

代码:

 1 import java.util.Scanner;
 2 
 3 public class test1 {
 4     public static int getMax(int arr[]) {
 5         int maxSum = arr[0];
 6         int tmp = 0;
 7         for (int i = 0; i < arr.length; i++) {
 8             if (tmp < 0) {
 9                 tmp = arr[i];
10                 if (tmp > 0 && maxSum < tmp) {
11                     maxSum = tmp;
12                 }
13             } else {
14                 tmp += arr[i];
15                 if (maxSum < tmp) {
16                     maxSum = tmp;
17                 }
18             }
19         }
20         return maxSum;
21     }
22 
23     public static int max(int arr[]) {
24         int max = arr[0];
25         for (int i = 0; i < arr.length; i++) {
26             if (max < arr[i]) {
27                 max = arr[i];
28             }
29         }
30         return max;
31     }
32 
33     public static void main(String[] args) {
34         int[] array = new int[100];
35         System.out.println("请输入数组的长度:");
36         Scanner sc = new Scanner(System.in);
37         int n = sc.nextInt();
38         System.out.println("请依次输入数组的元素:");
39         int[] result = new int[array.length];
40         for (int i = 0; i < n; i++) {
41             array[i] = sc.nextInt();
42         }
43         sc.close();
44         for (int i = 0; i < array.length; i++) {
45             int temp = array[0];
46             for (int i1 = 0; i1 < array.length - 1; i1++) {
47                 array[i1] = array[i1 + 1];
48             }
49             array[array.length - 1] = temp;
50             result[i] = getMax(array);
51         }
52         int r = max(result);
53         System.out.println("最大子数组和为:" + r);
54     }
55 }
View Code

猜你喜欢

转载自www.cnblogs.com/tkg1314/p/12375414.html
今日推荐