解题思路:贪心。把相邻两个数的差值进行从大到小排序,按照差值最大的进行分割。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double lf;
typedef unsigned long long ull;
typedef pair<ll,int>P;
const int inf = 0x7f7f7f7f;
const ll INF = 1e16;
const int N = 1e6+10;
const ull base = 131;
const ll mod = 1e9+7;
const double PI = acos(-1.0);
const double eps = 1e-4;
inline int read(){
int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){
if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
x=x*10+ch-'0';ch=getchar();}return x*f;}
inline string readstring(){
string str;char s=getchar();while(s==' '||s=='\n'||s=='\r'){
s=getchar();}while(s!=' '&&s!='\n'&&s!='\r'){
str+=s;s=getchar();}return str;}
int random(int n){
return (int)(rand()*rand())%n;}
void writestring(string s){
int n = s.size();for(int i = 0;i < n;i++){
printf("%c",s[i]);}}
ll fast_power(ll a,ll p){
ll ans = 1;
while(p){
if(p&1) ans = (ans*a)%mod;
p >>= 1;
a = (a*a)%mod;
}
return ans;
}
struct node{
int num;
int x,y;
}a[N];
int num[N];
bool cmp(node a,node b){
return a.num > b.num;
}
int main(){
int n = read(),m = read();
for(int i = 1;i <= n;i++){
num[i] = read();
}
for(int i = 1;i < n;i++){
a[i].num = num[i+1]-num[i];
a[i].x = i;
a[i].y = i+1;
}
sort(a+1,a+n,cmp);
if(m == n){
printf("%d\n",m);
return 0;
}
vector<int>b;
b.push_back(1);
b.push_back(n);
for(int i = 1;i < m;i++){
b.push_back(a[i].x);
b.push_back(a[i].y);
}
sort(b.begin(),b.end());
ll ans = m;
for(int i = 0;i < b.size();i++){
if(i%2 == 0){
ans -= num[b[i]];
}else {
ans += num[b[i]];
}
}
cout<<ans<<endl;
return 0;
}