#include using namespace std; typedef long long ll; const int INF = 100000000; int tmp; struct G { int count; int now; int dis; vector memo; G(int count, int now, int dis, vector memo) : count(count), now(now), dis(dis), memo(memo) {} bool operator>(const G &g) const { return dis > g.dis; //else return count > g.count; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; cin >> n >> m; vector d(m + 1, 0), minc(n + 1, INF); for (int i = 1; i <= m; i++) cin >> d[i]; priority_queue, greater > pq; pq.push(G(0, 0, 0, vector(m + 1, 0))); while (!pq.empty()) { G g = pq.top(); pq.pop(); if (g.count > n) break; g.memo[g.now] = 1; minc[g.count] = min(minc[g.count], g.dis); for (int i = 1; i <= m; i++) { if (g.memo[i]) continue; if (minc[g.count + 1] == INF) { pq.push(G(g.count + 1, i, g.dis + abs(d[i] - d[g.now]), g.memo)); } } } cout << minc[n] << "\n"; return 0; }