-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: prefix-sum-range added to leetcode problems along with test case
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
export class NumArray | ||
{ | ||
Inums: number[]; | ||
PrefixSum: number[] = []; | ||
constructor ( nums: number[] ) | ||
{ | ||
this.Inums = [ ...nums ]; | ||
for ( let i = 0; i < nums.length; i++ ) { | ||
if ( i === 0 ) { | ||
this.PrefixSum[ i ] = nums[ i ]; | ||
} else { | ||
this.PrefixSum[ i ] = nums[ i ] + nums[ i - 1 ]; | ||
} | ||
} | ||
} | ||
|
||
sumRange ( left: number, right: number ): number | ||
{ | ||
if ( left < 0 ) { | ||
throw new Error( "Bad Starting Index Range" ); | ||
} | ||
|
||
if ( right > this.Inums.length ) { | ||
throw new Error( "Bad Ending Index Range" ); | ||
} | ||
let sumRange = 0; | ||
for ( let i = left; i <= right; i++ ) { | ||
sumRange += this.PrefixSum[ i ]; | ||
} | ||
return sumRange; | ||
} | ||
} | ||
|
||
/** | ||
* Your NumArray object will be instantiated and called as such: | ||
* var obj = new NumArray(nums) | ||
* var param_1 = obj.sumRange(left,right) | ||
*/ |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { NumArray } from '../problems/prefix-sum-range'; | ||
|
||
describe( 'Sum of Cumulative Total in Range', () => | ||
{ | ||
it( 'should print 40 if the cumulative sum is checked from range from 1 to 4 in the array provided', () => | ||
{ | ||
expect( new NumArray( [ 1, 4, 5, 6, 9 ] ).sumRange( 1, 4 ) ).toBe( | ||
40 | ||
); | ||
} ); | ||
} ); |