zoukankan      html  css  js  c++  java
  • 求数组当中子数组最大和

    /*
    求最大子数组和(编程之美2.14)
    **author: DongChong
    **date :2013.6.12
    最简单的方法是采用编程珠玑上的扫描算法,但是别忘了判断
    数组当中都是负数的情况了。
    */
    #include <iostream>

    using namespace std;

    int main()
    {
    int a[]={-1,-2,-3,-10,-4,-7,-2,-5};

    int i=0;
    int sum=0;
    int max=0;
    int start=0;
    int maxStart=0,maxEnd=0;
    for(i=0;i<sizeof(a)/4;i++)
    {
    sum+=a[i];
    if(sum<=0)
    {
    start=i+1;
    sum=0;
    }
    else
    {
    if(sum>max)
    {
    max=sum;
    maxStart=start;
    maxEnd=i;
    }
    }

    }
    if(max==0)// Judge whether each elment of the array is negative
    {
    max=a[0];
    for(i=1;i<sizeof(a)/4;i++)
    {
    if(a[i]>max)
    {
    max=a[i];
    maxStart=i;
    maxEnd=i;
    }
    }
    }
    cout<<"max:"<<max<<endl;
    cout<<maxStart<<":"<<maxEnd<<endl;
    cout << "Hello world!" << endl;
    return 0;
    }

  • 相关阅读:
    asp.net 2.0 run
    Regular Expression
    assembly
    asp.net loading..
    session
    asp.net performance
    asp.net page order
    interface
    UVA 562 Dividing coins
    UVA 10003 Cutting Sticks
  • 原文地址:https://www.cnblogs.com/dyc0113/p/3132783.html
Copyright © 2011-2022 走看看