Ed
BAN USERThis could be done using combinations, here is JS code (run it in nodejs):
(function powerset(array) {
function _powerset(array, result, tmp, length, startIndex) {
for (var i = startIndex; i < length; ++i) {
tmp.push(array[i]);
result.push('{' + tmp.join(',') + '}');
if (i < length - 1) {
_powerset(array, result, tmp, length, i + 1);
}
--tmp.length;
}
}
var result = [];
var tmp = [];
_powerset(array, result, tmp, array.length, 0);
console.log(result.join(' '));
}([1, 2, 3]));
Output:
{1} {1,2} {1,2,3} {1,3} {2} {2,3} {3}
function(array) {
if (array.length < 2) {
return -1;
}
var sum1 = array[0];
var sum2 = array[1];
var length = array.length;
for (var i = 0, j = 1; i < length && j < length; i += 2, j += 2) {
if (i + 2 < length) {
sum1 += array[i + 2];
}
if (j + 2 < length) {
sum2 += array[j + 2];
}
}
return Math.max(sum1, sum2);
}
For the above examples, it seems it returns the correct answers:
1, 6, 2, 2, 3 // 6, 2 -> 8
1, 2, 3, 4, 5, 6 // 2, 4, 6 -> 12
Repleroydperry, Backend Developer at AppNexus
I am from the USA. I am 27 year old. I drive the train for my company Monk Home Funding ...
RepI believe in magic, power, aliens, parallel universe, god. I always dream about the powers and out of the world ...
JavaScript solution
- Ed March 06, 2013