B. Maximum of Maximums of Minimums
You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?
Definitions of subsegment and array splitting are given in notes.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105) — the size of the array a and the number of subsegments you have to split the array to.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Output
Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.
Examples
5 2
1 2 3 4 5
5
5 1
-4 -5 -3 -2 -1
-5
Note
A subsegment [l, r] (l ≤ r) of array a is the sequence al, al + 1, ..., ar.
Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).
In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.
In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4, - 5, - 3, - 2, - 1). The only minimum is min( - 4, - 5, - 3, - 2, - 1) = - 5. The resulting maximum is - 5.
题意
给出一个有n个整数的数组 a1, a2, ..., an 和一个整数k。你被要求把这个数组分成k 个非空的子段。 然后从每个k 个子段拿出最小值,再从这些最小值中拿出最大值。求这个最大值最大能为多少?
思路
一共可以分三种情况:
- 当k=1的时候,这个最大值一定是数组中的最小值
- 当k=2的时候,可以将数组分成两部分(废话),然后找到数组的第一个数字和最后一个数字中最大的那个就可以了
- 当k≥3的时候,可以将数组分割,让数组中最大的那个数单独放一组(这个是一定可以实现的),然后输出最大的数
代码
1 #include <bits/stdc++.h> 2 #define ll long long 3 #define ull unsigned long long 4 #define ms(a,b) memset(a,b,sizeof(a)) 5 const int inf=0x3f3f3f3f; 6 const ll INF=0x3f3f3f3f3f3f3f3f; 7 const int maxn=1e6+10; 8 const int mod=1e9+7; 9 const int maxm=1e3+10; 10 using namespace std; 11 int a[maxn]; 12 int main(int argc, char const *argv[]) 13 { 14 #ifndef ONLINE_JUDGE 15 freopen("/home/wzy/in.txt", "r", stdin); 16 freopen("/home/wzy/out.txt", "w", stdout); 17 srand((unsigned int)time(NULL)); 18 #endif 19 ios::sync_with_stdio(false); 20 cin.tie(0); 21 int n,k; 22 cin>>n>>k; 23 int maxx; 24 int place=0; 25 int minn; 26 for(int i=0;i<n;i++) 27 { 28 cin>>a[i]; 29 if(!i) 30 { 31 maxx=a[i]; 32 place=0; 33 minn=a[i]; 34 } 35 else if(maxx<a[i]) 36 place=i,maxx=a[i]; 37 minn=min(minn,a[i]); 38 } 39 if(k==1) 40 cout<<minn<<endl; 41 else if(k==2) 42 cout<<max(a[0],a[n-1])<<endl; 43 else 44 cout<<maxx<<endl; 45 #ifndef ONLINE_JUDGE 46 cerr<<"Time elapsed: "<<1.0*clock()/CLOCKS_PER_SEC<<" s."<<endl; 47 #endif 48 return 0; 49 }