[Data structure] some common algorithm ideas

Source: Internet
Author: User

1, divide and conquer thought
Calculates the maximum and of any successive sub-vectors in the input vector.
[31,-41,59,26,-53,58,97,-93,-23,84]
Direct algorithm:

[CPP]View Plaincopy
    1. Maxsofar=0
    2. For i = [0,n]
    3. sum = 0
    4. for j = [I, n]
    5. Sum + = X[j]
    6. Maxsofar=max (Maxsofar,sum)


Divide and conquer thought:
The vector is decomposed into two sub-vectors, solving the maximum and maximum of each vector, or the maximal value at the boundary of the child vector A and the sub-vector b

[CPP]View Plaincopy
  1. Float maxsum3 (l,u)
  2. if (L > U)
  3. return 0
  4. if (L = = u)
  5. return Max (0,x[1])
  6. m = (l + u)/2
  7. Lmax = SUM = 0
  8. For (i = m; i>=l;i--)
  9. Sum + = X[i]
  10. Lmax=max (Lmax,sum)
  11. Rmax=sum=0
  12. for i = (M,u]
  13. Sum+=x[i]
  14. Rmax=max (Rmax,sum)
  15. return Max (LMAX+RMAX,MAXSUM3 (l,m), maxsum3 (m+1,u))

The initial call is as follows: Answer=maxsum3 (0,n-1)
Decompose n vectors into n-1 and vector n

[CPP]View Plaincopy
      1. Maxsofar=0
      2. Maxendinghere=0
      3. For i = [0,n]
      4. Maxendinghere=max (maxendinghere+x[i],0)
      5. Maxsofar=max (Maxendinghere,maxsofar)

[Data structure] some common algorithm ideas

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.