|
| 1 | +classSolution { |
| 2 | +publiclongminCost(int[]nums,int[]cost) { |
| 3 | +intn =nums.length; |
| 4 | +int[][]numWithCost =newint[n][2]; |
| 5 | +for (inti =0;i <n;i++) { |
| 6 | +numWithCost[i] =newint[]{nums[i],cost[i]}; |
| 7 | + } |
| 8 | +Arrays.sort(numWithCost, (a,b) ->a[0] -b[0]); |
| 9 | +long[]prefixCost =newlong[n]; |
| 10 | +prefixCost[0] =numWithCost[0][1]; |
| 11 | +for (inti =1;i <n;i++) { |
| 12 | +prefixCost[i] =numWithCost[i][1] +prefixCost[i -1]; |
| 13 | + } |
| 14 | +longtotalCost =0; |
| 15 | +for (inti =1;i <n;i++) { |
| 16 | +totalCost +=1L *numWithCost[i][1] * (numWithCost[i][0] -numWithCost[0][0]); |
| 17 | + } |
| 18 | +longresult =totalCost; |
| 19 | +for (inti =1;i <n; ++i) { |
| 20 | +intgap =numWithCost[i][0] -numWithCost[i -1][0]; |
| 21 | +totalCost +=1L *prefixCost[i -1] *gap; |
| 22 | +totalCost -=1L * (prefixCost[n -1] -prefixCost[i -1]) *gap; |
| 23 | +result =Math.min(result,totalCost); |
| 24 | + } |
| 25 | +returnresult; |
| 26 | + } |
| 27 | +} |