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.
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).
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.
5 2 1 2 3 4 5
5
5 1 -4 -5 -3 -2 -1
-5
A subsegment [l, r] (l ≤ r) of array a is the sequence al, al + 1, ..., ar.
题目意思:
给你两个数字n和k 把这n个数字分成k段 让这k段中的k个最小值中的最大值最大
思路:
当k==1的时候我们直接输出最小值就好了
当k>2的时候我们可以单独把最大值隔开 然后能找到的最大值就一定是原序列的最大值本身
当k==2的时候 我用了一个前缀最小值数组和一个后缀最小值数组来维护前n项中的最小值和后n项中的最小值
本来这个操作需要一个for来遍历的 但是后来发现这个array[0] and array[n - 1] 一定是前缀最小值数组和后缀最小值数组中最大的值
所以只需要比较这两个数字的大小输出大的就好~~
比赛的时候我这道题莫名TL4次 就一个for循环 我至今不知道为什么~~~
#include <cstdio>
#include <cstring>
#include <algorithm>
const int inf = 0x7fffffff;
const int N = 100005;
using namespace std;
int array[N];
int main()
{
int n , k;
scanf("%d%d",&n,&k);
int maxx = -inf;
int minn = inf;
int max_id = 0;
for (int i = 0 ; i < n ; i++) {
scanf("%d",&array[i]);
if(array[i] > maxx) {
maxx = array[i];
max_id = i;
}
minn = min(minn , array[i]);
}
if(k == 1) {
printf("%d\n",minn);
} else if (k > 2) {
printf("%d\n",maxx);
}
else {
printf("%d\n",max(array[n-1],array[0]));
}
}