Skip to content

Commit 2d05047

Browse files
committed
Pick from both sides!
1 parent 2f4c08d commit 2d05047

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/pick-from-both-sides/
3+
4+
Problem Description
5+
6+
Given an integer array A of size N.
7+
You can pick B elements from either left or right end of the array A to get maximum sum.
8+
Find and return this maximum possible sum.
9+
NOTE: Suppose B = 4 and array A contains 10 elements then:
10+
You can pick first four elements or can pick last four elements or can pick 1 from front and
11+
3 from back etc . you need to return the maximum possible sum of elements you can pick.
12+
13+
Problem Constraints
14+
1 <= N <= 105
15+
1 <= B <= N
16+
-103 <= A[i] <= 103
17+
18+
Input Format
19+
First argument is an integer array A.
20+
Second argument is an integer B.
21+
22+
Output Format
23+
Return an integer denoting the maximum possible sum of elements you picked.
24+
25+
Example Input
26+
Input 1:
27+
A = [5, -2, 3 , 1, 2]
28+
B = 3
29+
30+
Input 2:
31+
A = [1, 2]
32+
B = 1
33+
34+
Example Output
35+
Output 1:
36+
8
37+
38+
Output 2:
39+
2
40+
41+
Example Explanation
42+
Explanation 1:
43+
Pick element 5 from front and element (1, 2) from back so we get 5 + 1 + 2 = 8
44+
45+
Explanation 2:
46+
Pick element 2 from end as this is the maximum we can get
47+
"""
48+
class Solution:
49+
# @param A : list of integers
50+
# @param B : integer
51+
# @return an integer
52+
def solve(self, A, B):
53+
cur_sum = 0
54+
for i in range(B):
55+
cur_sum += A[i]
56+
57+
if B == len(A):
58+
return cur_sum
59+
60+
max_sum = cur_sum
61+
index = B-1
62+
for i in range(len(A)-1, len(A)-B-1, -1):
63+
cur_sum += (A[i] - A[index])
64+
max_sum = max(max_sum, cur_sum)
65+
index -= 1
66+
return max_sum
67+

0 commit comments

Comments
 (0)