Home > front end >  Summation minimum time for help
Summation minimum time for help

Time:11-03

Xiao Ming math is not very good, if he were to calculate a + b take (a + b), there are n Numbers, let xiao Ming go to the n number and, xiao Ming calculating the n number of minimum time spent;

Note: each time to calculate the minimum number of two and, so that the total time is minimum,

Input: [1, 2, 3]
Output: 9
Description:
1 + 2 to 3 seconds
3 + 3 to 6 seconds
It will be altogether 9 seconds

Input: [1, 2, 3, 4, 5]
Output: 33
Description:
1 + 2 to 3 seconds
3 + 3 to 6 seconds
4 + 5 to 9 seconds
6 + 9 to 15 seconds

CodePudding user response:

this is going to do? Write a play?
 
The function sum_time (arr: number [], the sum: number) : number {
The console. The log (' the source data: '+ arr. Join (','));
//first order
Arr. Sort ((a, b)=& gt; A - b);
//minimum two sum
Const _sum=arr [0] + arr [1].
//accumulative
The sum +=_sum;
//process printing
The console. The log (arr [0] + '+' + arr [1] + '=' + (arr [0] + arr [1]));
The console. The log (+ sum computation time consuming:);
The console. The log ('==================================');
//the latest need to compute the array
Arr=[_sum] concat (arr. Slice (2));

//recursive
Arr. Length==1 & amp; & The console. The log (' end: : in the end, time-consuming: '+ sum);
Return arr. Length==1? Sum: sum_time (arr, sum)
}
Const arr=[1, 2, 3, 4, 5, 6, 7].
The console. The log (' start counting: \ n==================================');
Sum_time (arr, 0);

CodePudding user response:

Don't print process, in fact, at least can only four lines of code...
 
The function sum_time (arr: number [], the sum: number) : number {
//first order
Arr. Sort ((a, b)=& gt; A - b);
//minimum two sum
Const _sum=arr [0] + arr [1].
//accumulative
The sum +=_sum;
//the latest need to compute the array
Arr=[_sum] concat (arr. Slice (2));
//recursive
Return arr. Length==1? Sum: sum_time (arr, sum)
}

CodePudding user response:

Arr is not known, add a length of judgment to complete
 
The function sum_time2 (arr: number [], the sum: number=0) : number {
If (arr. Length & lt; 3) {
Return (arr & amp; & (arr [0] | | 0) + (arr [1] | | 0)) | | 0;
};
//first order
Arr. Sort ((a, b)=& gt; A - b);
//minimum two sum
Const _sum=arr [0] + arr [1].
//accumulative
The sum +=_sum;
//the latest need to compute the array
Arr=[_sum] concat (arr. Slice (2));
//recursive
Return arr. Length==1? Sum: sum_time2 (arr, sum)
}
  • Related