码迷,mamicode.com
首页 > 编程语言 > 详细

数组2

时间:2016-03-27 19:27:25      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

结对开发:朱建颖

#include<iostream>
using namespace std;
void main()
{
    // TODO Auto-generated method stub
    int i;
    int s = 0, sum = 0, head = 0, end = 0, h = 0, e = 0, x = 0;
    cout << "请输入数组长度:";
    cin >> x;
    int a[100];
    cout << "请输入数组中的数:";
    for (i = 0; i<x; i++)
    {
        cin >> a[i];
    }


    for (i = 0; i<x; i++)
    {
        s += a[i];
        if (s>0)
        {
            e++;
        }
        else
        {
            s = 0;
            h = i + 1;
            e++;
        }
        if (s>sum)
        {
            sum = s;
            head = h;
            end = e;
        }
    }
    if (s > 0)
    {
        head = h;
        i = 0;
        e = e - x;
        while (s > 0 && e != h - 1)
        {
            s += a[i];
            i++;
            e++;
            if (s > sum)
            {
                sum = s;
                end = e;
            }

        }
        if (end > head)
        {
            sum = sum / 2;
        }
        cout << "最大子数组的和为:" << sum << endl;
        cout << "最大子数组为:";
        if (end > head)
        {
            for (i = head; i < end; i++)
            {
                cout << a[i];
                cout << "   ";
            }
        }
        else
        {
            for (i = head; i < x; i++)
            {
                cout << a[i];
                cout << "   ";
            }
            for (i = 0; i < end; i++)
            {
                cout << a[i];
                cout << "   ";
            }
        }
    }
    system("pause");
}

 

数组2

标签:

原文地址:http://www.cnblogs.com/wooder/p/5326425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!