Last active
October 14, 2019 19:57
-
-
Save mpenkov/7297594 to your computer and use it in GitHub Desktop.
Coding for Interviews: Max Consecutive Sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Max Consecutive Sum</title> | |
</head> | |
<body> | |
Enter some integers: | |
<input type="text" id="txtInput" value="-1 5 6 -2 20 -50 4"></input> | |
<button onClick="btnOnClick();">Calculate</button> | |
<p> | |
Max consecutive sum is: <span id="divResult"></span> | |
</p> | |
<script> | |
function maxConsecutiveSum(numbers) { | |
var start = 0; | |
var end = 1; | |
var current_sum = numbers[0]; | |
var max_sum = 0; | |
while (true) { | |
if (current_sum > max_sum) { | |
max_sum = current_sum; | |
} | |
if (current_sum < 0) { | |
current_sum -= numbers[start++]; | |
continue; | |
} | |
if (end == numbers.length) { | |
break; | |
} | |
current_sum += numbers[end++]; | |
} | |
return max_sum; | |
} | |
function btnOnClick() { | |
var txtInput = document.getElementById("txtInput"); | |
var integers = txtInput.value.split(" "); | |
for (var i = 0; i < integers.length; ++i) { | |
integers[i] = parseInt(integers[i]); | |
} | |
var maxSum = maxConsecutiveSum(integers); | |
var divResult = document.getElementById("divResult"); | |
divResult.innerHTML = maxSum; | |
} | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def max_consecutive_sum(numbers): | |
"""Returns the maximum consecutive sum from the specified numbers.""" | |
assert len(numbers) | |
start = 0 | |
end = 1 | |
current_sum = max_sum = 0 | |
while True: | |
max_sum = max(current_sum, max_sum) | |
if current_sum < 0: | |
current_sum -= numbers[start] | |
start += 1 | |
continue | |
if end == len(numbers): | |
break | |
current_sum += numbers[end] | |
end += 1 | |
return max_sum | |
def main(): | |
import sys | |
numbers = map(int, sys.argv[1:]) | |
print max_consecutive_sum(numbers) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment