Problem:
Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Solution 1:
public int[] RunningSum(int[] nums) {
int [] arr=new int[nums.Length];
arr[0]=nums[0];
for(int i=1;i<nums.Length;i++){
arr[i]=Sum(nums,i);
}
return arr;
}
public int Sum(int[] nums,int num){
int sum=0;
for(int i=0;i<nums.Length;i++){
if(i<=num){
sum=sum+nums[i];
}
else{
break;
}
}
return sum;
}
Solution 2:
The simple and easiest solution,
public int[] RunningSum(int[] nums) {
for(int i=1;i<nums.Length;i++){
nums[i]+=nums[i-1];
}
return nums;
}
Need help?
Read this post again, if you have any confusion, or else add your questions to Community