[LeetCode] K-Concatenation Maximum Sum

1191. K-Concatenation Maximum Sum

Given an integer array arr and an integer k, modify the array by repeating it k times.

For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

As the answer can be very large, return the answer modulo 10^9 + 7.

c++
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
class Solution {
public:
int kConcatenationMaxSum(vector<int>& arr, int k) {
long long totalSum = 0;
long long answer = 0;
long long maxValue = 0;
long long minValue = 0;
for(int i = 0; i < arr.size(); i++) {
totalSum += arr[i];
maxValue = max(maxValue, totalSum);
minValue = min(minValue, totalSum);

answer = max(answer, totalSum - minValue);
}

if(k > 1) {
answer = max(answer, max(totalSum - minValue + maxValue, totalSum * (k - 1) + max(totalSum - minValue, maxValue)));

if(k > 2) {
answer = max(answer, totalSum * (k - 2) + totalSum - minValue + maxValue);
}
}

return max(totalSum * k, answer) % 1000000007;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/20/PS/LeetCode/k-concatenation-maximum-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
2 comments
Anonymous
Markdown is supported
@hyunstory
hyunstorycommentedabout 4 years ago

하영님 안녕하세요. 저는 세종대학교를 졸업한 취준생입니다. 다름이 아니라, 궁금한 점이 있어서 여쭈어보고 싶은게 있습니다. 혹시 연락 가능하실까요..?
연락할 수 있는 수단을 찾을 수 없어서 이렇게 댓글로 남겨드립니다.

@SongHayoung
SongHayoungcommentedabout 4 years ago

@hyunstory
하영님 안녕하세요. 저는 세종대학교를 졸업한 취준생입니다. 다름이 아니라, 궁금한 점이 있어서 여쭈어보고 싶은게 있습니다. 혹시 연락 가능하실까요..?
연락할 수 있는 수단을 찾을 수 없어서 이렇게 댓글로 남겨드립니다.

안녕하세요, 송하영입니다.
https://open.kakao.com/o/sVqAV0Ic 이 주소로 연락 주시면 좋을꺼 같아요~