最佳植树距离

#include <iostream>

#include <algorithm>

#include <vector>

using namespace std;

int minSpace(vector<int>& holes, int target)

{

sort(holes.begin(), holes.end());

int left = 0;

int right = holes.back() - holes.front();

int answer = -1;

while (left <= right)

{

int mid = left + (right - left) / 2;

int count = 1;

int previous = holes[0];

for (int i = 1; i < holes.size(); i++)

{

if (holes[i] - previous >= mid)

{

count++;

previous = holes[i];

if (count >= target)

{

answer = mid;

left = mid + 1;

break;

}

}

}

if (count < target)

{

right = mid - 1;

}

}

return answer;

}

int main()

{

int n;

cin >> n;

vector<int> holes(n);

for (int i = 0; i < n; i++)

{

cin >> holes[i];

}

int target;

cin >> target;

int result = minSpace(holes, target);

cout << result << endl;

return 0;

}

相关推荐
曙曙学编程6 分钟前
stm32——独立看门狗,RTC
c语言·c++·stm32·单片机·嵌入式硬件
励志不掉头发的内向程序员13 分钟前
C++进阶——多态
开发语言·c++·学习
空白到白1 小时前
决策树-面试题
算法·决策树·机器学习
flashlight_hi1 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
前端世界1 小时前
HarmonyOS 数据处理性能优化:算法 + 异步 + 分布式实战
算法·性能优化·harmonyos
YS_Geo1 小时前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis
楼田莉子1 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
njxiejing1 小时前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
tju新生代魔迷1 小时前
数据结构:单链表以及链表题
数据结构·链表
dragoooon341 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法