补种未成活胡杨树

华为算法面试 求助
//补种未成活胡杨树
//某沙漠新种植N颗胡杨(编号1~N),一个月后,有M颗未能成活。现可补种K颗(只可补种,不可新种),请问怎样补种,可以得到最多的连续胡杨树?
输入  N 总种植数量
    M  未成活数量
    M个空格分割的数,按编号从小到大排列
    K 最多可以补种的数量
    其中 1<=N<1000 1<=M<N 0<=K<=M
    实例 输入
       10
       3
       2 4 7
       1
       输出
       6
       说明 补种第7颗 可得到5,6,7,8,9,10连续胡杨树
#华为##面试题目#
全部评论
滑动窗口问题,只是这里的判断条件不一样,需要判断用来记录连续值的数组arr内含有未成活位置的数量是否大于补种的数量,如果大于,arr需要一直执行shift(),一直到下一个补种位置,不大于的话可以一直往arr添加胡杨树
1 回复 分享
发布于 2022-05-26 16:02
连续的,那补种的也只能是连续的了,for m for n把所有假设都算出来提max
1 回复 分享
发布于 2022-03-06 10:51
应该是个滑动窗口题,保证你窗口内有k个未成活,然后求最大窗口大小就行。左边少一个,右边就找一个新的
6 回复 分享
发布于 2022-03-07 22:33
Scanner in = new Scanner(System.in); int n = in.nextInt(); int M = in.nextInt(); int []temp = new int[n+1]; for(int i =0;i<m>k){ if(temp[l]==1) curd--; l++; } } res = Math.max(r-l+1,res); r++; } System.out.println(res);</m>
点赞 回复 分享
发布于 2024-05-21 15:25 广东
public class TreeReplant {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         //胡杨总数         int n = scanner.nextInt();         //死亡胡杨数目         int m = scanner.nextInt();         //死亡胡杨编号数组         List<Integer> array = new ArrayList<>();         for (int i=0;i<m;i++) {             array.add(scanner.nextInt());         }         //补种数量         int k = scanner.nextInt();         //记录最大值         int max = 0;         //从左向右移动滑动窗口,这里的i标记的是窗口的左边界         for (int i=0;i<=m-k;i++) {             if (i == 0) {                 //滑动窗口在数组最左边                 max = Math.max(max, array.get(i+k) - 1);             }else if (i == m-k) {                 //滑动窗口在数组最右边                 max = Math.max(max, n - array.get(i-1));             }else {                 //滑动窗口在数组中间某个位置                 max = Math.max(max, array.get(i+k) - array.get(i-1) - 1);             }         }         System.out.println(max);     } }
点赞 回复 分享
发布于 2023-07-02 10:44 陕西
为啥只有我用dfs呢
点赞 回复 分享
发布于 2022-09-26 13:42 北京
感觉可以用排列去做
点赞 回复 分享
发布于 2022-09-23 16:13 浙江
像是滑窗?看成01序列,求0的count在k下的最长序列?
点赞 回复 分享
发布于 2022-03-06 10:16

相关推荐

评论
6
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务