-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pick from both sides!
72 lines (40 loc) · 1.04 KB
/
Pick from both sides!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Problem Description
Given an integer array A of size N.
You can pick B elements from either left or right end of the array A to get maximum sum.
Find and return this maximum possible sum.
NOTE: Suppose B = 4 and array A contains 10 elements then
You can pick first four elements or can pick last four elements or can pick 1 from front and 3 from back etc . you need to return the maximum possible sum of elements you can pick.
Problem Constraints
1 <= N <= 105
1 <= B <= N
-103 <= A[i] <= 103
Input Format
First argument is an integer array A.
Second argument is an integer B.
Output Format
Return an integer denoting the maximum possible sum of elements you picked.
Example Input
Input 1:
A = [5, -2, 3 , 1, 2]
B = 3
Input 2:
A = [1, 2]
B = 1
*/
int Solution::solve(vector<int> &A, int B) {
int n = A.size();
int result = 0;
for(int i = 0; i < B; i++)
{
result += A[i];
}
int sum = result;
for(int i = 0; i < B; i++)
{
sum -= A[B - 1 - i];
sum += A[n - 1- i];
result = max(result, sum);
}
return result;
}