-
Notifications
You must be signed in to change notification settings - Fork 0
/
array sum upto given number.txt
71 lines (37 loc) · 1.04 KB
/
array sum upto given number.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
Given an array of integers Arr of size N and a number K. Return the maximum sum of a subarray of size K.
Example 1:
Input:
N = 4, K = 2
Arr = [100, 200, 300, 400]
Output:
700
Explanation:
Arr3 + Arr4 =700,
which is maximum.
Example 2:
Input:
N = 4, K = 4
Arr = [100, 200, 300, 400]
Output:
1000
Explanation:
Arr1 + Arr2 + Arr3
+ Arr4 =1000,
which is maximum.
Your Task:
You don't need to read input or print anything. Your task is to complete the function maximumSumSubarray() which takes the integer k, vector Arr with size N, containing the elements of the array and returns the maximum sum of a subarray of size K.
class Solution{
public:
int maximumSumSubarray(int K, vector<int> &Arr, int N){
int res = 0;
for (int i=0; i<K; i++)
res += Arr[i];
int curr_sum = res;
for (int i=K; i<N; i++)
{
curr_sum += Arr[i] - Arr[i-K];
res = max(res, curr_sum);
}
return res;
}
};