Skip to content

Commit 70e754f

Browse files
committed
Solved the Max Array Sum.
1 parent acc74f5 commit 70e754f

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Note: Few codes were solved in C# (I've written them a long time ago), I'll conv
6767

6868
- [Count Triplets](challenges/countTriplets.js)
6969
- [Frequency Queries](challenges/freqQuery.js)
70+
- [Max Array Sum](challenges/maxSubsetSum.js)
7071
- [Minimum Swaps 2](challenges/minimumSwaps.js)
7172
- [Special String Again](challenges/substrCount.js)
7273

challenges/maxSubsetSum.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//+ Jonas Raoni Soares Silva
2+
//@ http://raoni.org
3+
4+
function maxSubsetSum(arr) {
5+
let sum = 0;
6+
// Head is the current best index
7+
// As we go walking through the array, we're keeping the sums saved, so it becomes easier to switch the path
8+
for (let previous = -1, head = -2, i = -1, l = arr.length; ++i < l; ) {
9+
const v = arr[i];
10+
// Skip non-positive numbers
11+
if (v < 1)
12+
continue;
13+
// If it's an adjacent item, add to the sum (also replace the number by the sum at this position)
14+
if (head + 1 != i)
15+
arr[i] = sum += v;
16+
else {
17+
// Does the previous adjacent item offer a bigger sum?
18+
const newSum = arr[i] += previous > -1 ? arr[previous] : 0;
19+
if (newSum <= sum) {
20+
// If not, just mark it as a valid adjacent item
21+
previous = i;
22+
continue;
23+
}
24+
sum = newSum;
25+
}
26+
// If we ended up here, the sum was updated, so we need to update our indexes
27+
previous = head;
28+
head = i;
29+
}
30+
return sum;
31+
}

0 commit comments

Comments
 (0)