class Solution {
public int[] runningSum(int[] nums) {
int[] ans = new int[nums.length];
ans[0] = nums[0];
for (int i = 1; i < nums.length; i++)
ans[i] = ans[i-1] + nums[i];
return ans;
}
}
// Running sum of 1d array
// Iterative
fn running_sum1(nums: Vec<i32>) -> Vec<i32> {
let mut arr = vec![nums[0]];
for i in 1..nums.len() {
arr.push(nums[i] + arr[i - 1]);
}
arr
}
// Functional
fn running_sum2(nums: Vec<i32>) -> Vec<i32> {
let mut sum = 0;
nums.into_iter().map(|i| {sum += i; sum}).collect::<Vec<i32>>()
}
fn main() {
println!("Running sum = {:?} ", running_sum1(vec![4,1,7,10,1]));
println!("Running sum = {:?} ", running_sum2(vec![4,1,7,10,1]));
}
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].