Calculate the maximum sum of consecutive k numbers in the N number of unordered orders.

Source: Internet
Author: User

1. There is an integer array whose elements contain positive integers and negative integers. Find the largest subset of all its child sets.
For example, [12,-,-,]. The result is 63 [12,-].
The complexity is O (n ).

Int func (int n, int A [])
{
Int sum = 0, B = 0, I;

For (I = 1; I <= N; I ++)
{
If (B> 0) B + = A [I];
Else B = A [I];
If (B> sum) sum = B;
}
Return sum;
}

 

2. Calculate the maximum sum of consecutive k numbers in the N number of unordered orders.

Specific ideas:

Assume nItemsQuantity: A1 A2 A3 A4 A5...

AllContinuousKItemsQuantityThen, first find A1 ~ Sum of AK

A (2 )~ A (K+ 1) sum-A1 + (K+ 1) ------------------- (1)

A (3 )~ A (K+ 2) sum = (1) result-a (2) + (K+ 2)

Code
# Include <iostream>
Using namespace STD;

Int main ()
{
Int N, K;

Int * num;

Int sum;
Int Max;

Cout <"Enter the number N :";
Cin> N;
Cout <"Enter K :";
Cin> K;

If (! (N> 0 & K <= n ))
{
Return 0;
}

Num = new int [N];

Cout <"Enter n integers :";
Sum = 0;
For (INT I = 0; I <n; I ++)
{
Cin> num [I];
If (I <k) sum + = num [I]; // when reading a number, calculate the sum of the first K digits
}
Max = sum;

For (INT I = K; I <n; I ++)
{
Sum = sum-num [I-K] + num [I]; // sum of the next K numbers, is equal to the sum calculated just now minus the Starting number num [I-K] plus the new number num [I]
If (sum> MAX)
{
Max = sum;
}
}

Cout <max <Endl;

Delete [] num;
System ("pause ");
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.