Returns a continuous subsequence to maximize the sum (deformation)

Source: Internet
Author: User

An old question in programming: An array that finds continuous subsequences to maximize the sum. We can use the linear scanning algorithm to solve this problem. After this problem is transformed, it becomes: finding continuous subsequences so that they are closest to a certain number. The original time complexity is linear. We can accumulate an array, sort it, and calculate the adjacent difference. The number closest to k is what we want. The Code is as follows:

  1. IntApproximate (Int* PArry,IntLen)
  2. {
  3. Int* Cum = 0;
  4. Int* Realarry =New Int[Len + 1];
  5. Realarry [0] = 0;
  6. Cum = realarry + 1; // cum [-1] = 0
  7. // Accumulate and store the sum of pArry [0... I] In cum [I]
  8. For(IntI = 0; I <len; I ++)
  9. {
  10. Cum [I] = cum [I-1] + pArry [I];
  11. }
  12. Sort (cum, cum + len); // sorts cum
  13. IntIMin = cum [1]-cum [0];
  14. For(IntK = 1; k <len; k ++)
  15. {
  16. IMin = min (iMin, cum [k]-cum [k-1]); // returns the smallest difference between two adjacent elements.
  17. }
  18. ReturnIMin;
  19. }

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.