> For the complete documentation index, see [llms.txt](https://shenjunhong.gitbook.io/blog/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shenjunhong.gitbook.io/blog/suan-fa/1029-liang-di-diao-du.md).

# 1029. 两地调度

公司计划面试 2n 人。给你一个数组 costs ，其中 costs\[i] = \[aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ，飞往 b 市的费用为 bCosti 。

返回将每个人都飞到 a 、b 中某座城市的最低费用，要求每个城市都有 n 人抵达。

输入：costs = \[\[10,20],\[30,200],\[400,50],\[30,20]] 输出：110 解释： 第一个人去 a 市，费用为 10。 第二个人去 a 市，费用为 30。 第三个人去 b 市，费用为 50。 第四个人去 b 市，费用为 20。

最低总费用为 10 + 30 + 50 + 20 = 110，每个城市都有一半的人在面试。

```javascript
* @param {number[][]} costs
* @return {number}
 */
var twoCitySchedCost = function(costs) {
    //1. 计算费用
    const sumB = costs.reduce((acc, cur) => acc+ cur[1], 0);
    const diff = costs.map(cost => cost[0] - cost[1])
    diff.sort((a,b) => a -b)
    diff.length = diffs.length / 2;
    const sumA = diffs.reduce((acc, cur) => acc + cur, 0)
    return sumB + sumA
};

// 为啥感觉就是求最小的值
先所有2n人飞b，总费用为sum；
改变其中n人的行程，那么就需要付出aCost-bCost的代价；
而最终希望的结果是sum尽可能地小，故只要aCost-bCost尽可能小即可；
对aCost-bCost进行排序，选择最小的前n个aCost-bCost，将这n个aCost-bCost加到sum即可。
/**
```

```javascript
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

```

reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数，每一次运行 reducer 会将先前元素的计算结果作为参数传入，最后将其结果汇总为单个返回值。

第一次执行回调函数时，不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行，则需要传递初始值。否则，数组索引为 0 的元素将被作为初始值 initialValue，迭代器将从第二个元素开始执行（索引为 1 而不是 0）。

说人话就是 看有没有传初始值 没有的话 将会选择数组索引为0 的元素将作为初始值，迭代器将从第二个元素开始执行（索引为1而不是0）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shenjunhong.gitbook.io/blog/suan-fa/1029-liang-di-diao-du.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
