Hunter algorithms-find and maximize sub-arrays from an array, which may have negative numbers.

Source: Internet
Author: User

Question: Find and the largest sub-array from an array. The array may have negative numbers.

Idea:Perform the following steps to list all the situations and make a comparison record!

    • Compile a method for calculating the sum within a certain range of arrays.
    • Traverse all the situations in sequence and record the maximum value.

The C ++ implementation is as follows:

// ================================================ ==================================================================== // Name: maxsubarray. CPP // Author: Jue // version: // copyright: Your copyright notice // Description: Hello world in C ++, ANSI-style // ========================================== ========================================================== = # include <iostream> using namespace STD; class mydata {public: int startindex; int endindex; int maxdata ;}; int getsum (INT datas [], int start, int end) {int sum = 0; for (INT I = start; I <= end; I ++) {sum + = datas [I];} return sum;} mydata * findmaxsubarray (INT datas [], int length) {mydata * Data = new mydata; For (INT I = 0; I <length; I ++) {for (Int J = I; j <length; j ++) {int sum = getsum (datas, I, j); If (I = 0 & J = 0) | (sum> data-> maxdata) {data-> maxdata = sum; data-> startindex = I; data-> endindex = J ;}} return data ;} int main () {int datas [] = {1,-2,-3}; mydata * Data = findmaxsubarray (datas, 3 ); cout <"max =" <data-> maxdata <"Start:" <data-> startindex <"end:" <data-> endindex; return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.