Sum of difference

AtCoder
IDabc186_d
Time2000ms
Memory256MB
Difficulty
Given are $N$ integers $A_1,\ldots,A_N$. Find the sum of $|A_i-A_j|$ over all pairs $i,j$ such that $1\leq i < j \leq N$. In other words, find $\displaystyle{\sum_{i=1}^{N-1}\sum_{j=i+1}^{N} |A_i-A_j|}$. ## Constraints * $2 \leq N \leq 2 \times 10^5$ * $|A_i|\leq 10^8$ * $A_i$ is an integer. ## Input Input is given from Standard Input in the following format: $N$ $A_1$ $\ldots$ $A_N$ [samples]
Samples
Input #1
3
5 1 2
Output #1
8

We have $|5-1|+|5-2|+|1-2|=8$.
Input #2
5
31 41 59 26 53
Output #2
176
API Response (JSON)
{
  "problem": {
    "name": "Sum of difference",
    "description": {
      "content": "Given are $N$ integers $A_1,\\ldots,A_N$. Find the sum of $|A_i-A_j|$ over all pairs $i,j$ such that $1\\leq i < j \\leq N$. In other words, find $\\displaystyle{\\sum_{i=1}^{N-1}\\sum_{j=i+1}^{N} |A_i-A_j|",
      "description_type": "Markdown"
    },
    "platform": "AtCoder",
    "limit": {
      "time_limit": 2000,
      "memory_limit": 262144
    },
    "difficulty": "None",
    "is_remote": true,
    "is_sync": true,
    "sync_url": null,
    "sign": "abc186_d"
  },
  "statements": [
    {
      "statement_type": "Markdown",
      "content": "Given are $N$ integers $A_1,\\ldots,A_N$.\nFind the sum of $|A_i-A_j|$ over all pairs $i,j$ such that $1\\leq i < j \\leq N$.\nIn other words, find $\\displaystyle{\\sum_{i=1}^{N-1}\\sum_{j=i+1}^{N} |A_i-A_j|...",
      "is_translate": false,
      "language": "English"
    }
  ]
}
Full JSON Raw Segments