File tree 1 file changed +28
-17
lines changed
scripts/algorithms/M/Minimum Average Difference
1 file changed +28
-17
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 83 ms (Top 27.27%) | Memory: 65.10 MB (Top 27.27%)
1
2
2
- `` ` /**
3
+ /**
3
4
* @param {number[] } nums
4
5
* @return {number }
5
6
*/
6
- var minimumAverageDifference = function ( nums ) {
7
- if ( nums . length == 1 ) return 0 ;
8
- let mins = 100000 , resultIndex , leftTotal = 0 ;
9
- let rightTotal = nums . reduce ( ( a , b ) => a + b ) ;
10
- let numLength = nums . length ;
11
- nums . forEach ( ( data , index ) => {
12
- leftTotal += data ;
13
- rightTotal -= data ;
14
- let currentAverageDiff = Math . abs ( Math . floor ( leftTotal / ( index + 1 ) ) - Math . floor ( rightTotal / ( numLength - index - 1 ) || 0 ) ) ;
15
- if ( currentAverageDiff < mins ) {
16
- resultIndex = index ;
17
- mins = currentAverageDiff ;
18
- }
19
- } ) ;
20
- return resultIndex ;
21
- } ;
7
+ var minimumAverageDifference = function ( nums ) {
8
+ let firstSum = 0 ;
9
+ let lastSum = 0 ;
10
+
11
+ for ( let num of nums ) lastSum += num ;
12
+
13
+ let minAvg = Number . POSITIVE_INFINITY ;
14
+ let minAvgIndex = 0 ;
15
+
16
+ for ( let i = 0 ; i < nums . length ; i ++ ) {
17
+ firstSum += nums [ i ] ;
18
+ lastSum -= nums [ i ] ;
19
+
20
+ if ( i !== nums . length - 1 )
21
+ currAvg = Math . abs ( Math . floor ( firstSum / ( i + 1 ) ) - Math . floor ( lastSum / ( nums . length - i - 1 ) ) ) ;
22
+ else
23
+ currAvg = Math . abs ( Math . floor ( firstSum / ( i + 1 ) ) ) ;
24
+
25
+ if ( currAvg < minAvg ) {
26
+ minAvg = currAvg ;
27
+ minAvgIndex = i ;
28
+ }
29
+ }
30
+
31
+ return minAvgIndex ;
32
+ } ;
You can’t perform that action at this time.
0 commit comments