-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum of element iin a given range.txt
97 lines (50 loc) · 1.37 KB
/
sum of element iin a given range.txt
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
Example Output
Output 1:
8
Output 2:
2
Example Explanation
Explanation 1:
Pick element 5 from front and element (1, 2) from back so we get 5 + 1 + 2 = 8
Explanation 2:
Pick element 2 from end as this is the maximum we can get
Solution
int Solution::solve(vector<int> &arr, int B)
{
int n = arr.size();
int sum = 0 , result = 0;
for(int i = 0 ; i < B ; i++)
{
result = result + arr[i];
}
sum = result;
for(int i = 0 ; i < B ; i++)
{
sum = sum - arr[B-1-i];
sum = sum + arr[n-1-i];
result = max(result , sum);
}
return result;
}