數組中子序列最大和演算法

來源:互聯網
上載者:User

昨天有同事去別的公司面試,考了這樣一道題,說寫得不好,問能不能有時間複雜度為數組長度的演算法,這個應該不難,寫了段代碼,執行上應該沒錯。

int main(int argc, char* argv[]){int a[]={10,3,-5,16,90,-100,90,6,-7};int n =sizeof(a)/sizeof(int);int max = 0;int tmpmax = 0;for(int i=0;i<n;i++){if(tmpmax+a[i]>max){tmpmax = max = tmpmax+a[i];}else{tmpmax = tmpmax+a[i];if(tmpmax<0)tmpmax = 0;}}cout<<"MaxValue: "<<max<<endl;return 0; }嘿嘿,誰能看出那個數組中和最大的子序列是什嗎??

 應該是最簡單的演算法了,在網上搜了下,好些人寫得有問題,誤人子弟啊。

上面是沒有考慮全負的情況,修正如下:

 

    int a[]={-10,3,9,-16,-90,-100,-90,6,-7};
    int n =sizeof(a)/sizeof(int);

    int max = a[0];
    int tmpmax = 0;

    for(int i=0;i<n;i++)
    {
        if((tmpmax=tmpmax+a[i])>max)
        {
            max = tmpmax;
        }
        else
        {
            if(tmpmax<0)
            {
                if(max<0)
                    if(a[i]>max)
                        max = a[i];
                else
                    tmpmax = 0;
            }
                
        }
    }

    cout<<"MaxValue: "<<max<<endl;
如果全負實際是做了一遍選擇排序。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.