Last active
June 29, 2022 14:51
-
-
Save MorrisLaw/03c39a43513397f7d8dc021137169a22 to your computer and use it in GitHub Desktop.
running sum
This file contains 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
// O(n) time, O(n) space | |
func runningSum(nums []int) []int { | |
if len(nums) <= 1 { return nums } | |
var result []int // O(n) space complexity | |
result = append(result, nums[0]) | |
for i := 1; i < len(nums); i++ { // O(n) time complexity | |
result = append(result, nums[i]+(result[i-1])) | |
} | |
return result | |
} | |
// O(n) time, O(1) space | |
func runningSum(nums []int) []int { | |
if len(nums) <= 1 { return nums } | |
runSum := nums[0] | |
for i := 1; i < len(nums); i++ { // O(n) time complexity | |
nums[i-1] = runSum | |
runSum += nums[i] | |
} | |
nums[len(nums)-1] = runSum | |
return nums | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment