forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1191.cpp
More file actions
executable file
·40 lines (33 loc) · 892 Bytes
/
LC1191.cpp
File metadata and controls
executable file
·40 lines (33 loc) · 892 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/k-concatenation-maximum-sum/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int kConcatenationMaxSum(vector<int>& arr, int k) {
int sum, left, mid, right, max_sum;
sum = left = mid = right = max_sum = 0;
// left sum
kadane_algorithm(sum, max_sum, arr);
left = sum;
if (k == 1)
return max_sum;
// mid sum
kadane_algorithm(sum, max_sum, arr);
mid = sum - left;
// right sum
kadane_algorithm(sum, max_sum, arr);
right = max_sum - (left + mid);
// total sum
max_sum = (left + (long long) mid * (k - 2) + right) % (int) (1e9 + 7);
return max_sum;
}
void kadane_algorithm(int& sum, int& max_sum, vector<int>& arr) {
for (int i = 0 ; i < arr.size() ; i++) {
sum = max(arr[i], arr[i] + sum);
max_sum = max(sum, max_sum);
}
}
};