Skip to content

Commit af963bb

Browse files
committed
Add solution #1191
1 parent 7d34f37 commit af963bb

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,174 LeetCode solutions in JavaScript
1+
# 1,175 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -923,6 +923,7 @@
923923
1187|[Make Array Strictly Increasing](./solutions/1187-make-array-strictly-increasing.js)|Hard|
924924
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|
925925
1190|[Reverse Substrings Between Each Pair of Parentheses](./solutions/1190-reverse-substrings-between-each-pair-of-parentheses.js)|Medium|
926+
1191|[K-Concatenation Maximum Sum](./solutions/1191-k-concatenation-maximum-sum.js)|Medium|
926927
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
927928
1206|[Design Skiplist](./solutions/1206-design-skiplist.js)|Hard|
928929
1207|[Unique Number of Occurrences](./solutions/1207-unique-number-of-occurrences.js)|Easy|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 1191. K-Concatenation Maximum Sum
3+
* https://leetcode.com/problems/k-concatenation-maximum-sum/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array arr and an integer k, modify the array by repeating it k times.
7+
*
8+
* For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].
9+
*
10+
* Return the maximum sub-array sum in the modified array. Note that the length of the sub-array
11+
* can be 0 and its sum in that case is 0.
12+
*
13+
* As the answer can be very large, return the answer modulo 109 + 7.
14+
*/
15+
16+
/**
17+
* @param {number[]} arr
18+
* @param {number} k
19+
* @return {number}
20+
*/
21+
var kConcatenationMaxSum = function(arr, k) {
22+
const MOD = 1e9 + 7;
23+
const arraySum = arr.reduce((sum, num) => sum + num, 0);
24+
const maxSingle = helper(arr);
25+
26+
if (k === 1) return maxSingle;
27+
28+
const doubleArray = [...arr, ...arr];
29+
const maxDouble = helper(doubleArray);
30+
31+
if (arraySum > 0) {
32+
return Number((BigInt(maxDouble) + BigInt(arraySum) * BigInt(k - 2)) % BigInt(MOD));
33+
}
34+
35+
return maxDouble;
36+
};
37+
38+
function helper(arr) {
39+
let maxSoFar = 0;
40+
let maxEndingHere = 0;
41+
42+
for (const num of arr) {
43+
maxEndingHere = Math.max(0, maxEndingHere + num);
44+
maxSoFar = Math.max(maxSoFar, maxEndingHere);
45+
}
46+
47+
return maxSoFar;
48+
}

0 commit comments

Comments
 (0)