代码改变世界

求一个数组相邻数的最大和,并且得到开始编号和结束编号(原创)

  音乐让我说  阅读(486)  评论(0编辑  收藏  举报

代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
static void GetMax()
{
    int[] items = new int[] { 31, -41, 59, 26, -53, 58, 97, -93, -23, 84 };
 
    //int[] items = new int[] { 31, -41, -59, -26};
 
    //int[] items = new int[] { -10,20,-5};
 
    int beginIndex = 0;
    int? maxTotal = null;
    int endIndex = 0;
 
    int itemsLength = items.Length;
    if (itemsLength == 1)
    {
        //只有一个元素
        maxTotal = items[0];
        beginIndex = 1;
        endIndex = 1;
    }
    else if (itemsLength == 2)
    {
        //只有二个元素
        if (items[0] > items[1])
        {
            maxTotal = items[0];
            beginIndex = 1;
            endIndex = 1;
        }
        else
        {
            maxTotal = items[1];
            beginIndex = 2;
            endIndex = 2;
        }
        if ((items[0] + items[1]) > maxTotal)
        {
            maxTotal = items[0] + items[1];
            beginIndex = 1;
            endIndex = 2;
        }
    }
    else
    {
        for (int i = 0; i < itemsLength; i++)
        {
            for (int j = i + 1; j < itemsLength; j++)
            {
                int tempMax = items[i];
                for (int k = (i + 1); k <= j; k++)
                {
                    tempMax += items[k];
                }
                if (!maxTotal.HasValue || tempMax > maxTotal)
                {
                    beginIndex = i + 1;
                    endIndex = j + 1;
                    maxTotal = tempMax;
                }
            }
        }
    }
    Console.WriteLine("最大值:" + maxTotal);
    Console.WriteLine("开始编号为:" + beginIndex);
    Console.WriteLine("结束编号为:" + endIndex);
    Console.ReadKey();
}

 

等待更新...

点击右上角即可分享
微信分享提示