您的位置:首页 > 编程语言 > Java开发

Java基础练习05--数组中最长递增子序列长度

2018-12-05 10:37 127 查看

小猴子下山,沿着下山的路有一排桃树,每棵树都结了一些桃子。小猴子想摘桃子,但是有一些条件需要遵守,小猴子只能沿着下 山的方向走,不能回头,每颗树最多摘一个,而且一旦摘了一棵树的桃子,就不能再摘比这棵树结的桃子少的树上的桃子。那么小 猴子最多能摘到几颗桃子呢?
举例说明,比如有5棵树,分别结了10,4,5,12,8颗桃子,
那么小猴子最多能摘3颗桃子,来 自于结了4,5,8颗桃子的桃树

其实,这就是给出了一个整型数组,让你求出其中最长的递增子序列长度。

代码:

[code]package cn.drc.programming.test;

import java.util.Arrays;
import java.util.Scanner;

/**
* 猴子摘桃
* @author drc
*/
public class MaxAmountOfPeaches {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int trees = sc.nextInt(); // 几棵树
int[] treePeaches = new int[trees]; // 树上的桃子数
for(int x=0; x<trees; x++) { // 输入桃子数
treePeaches[x] = sc.nextInt();
}
sc.close();
int maxPeaches = getMaxPeaches(treePeaches);

System.out.println("猴子最多可以摘"  + maxPeaches + "颗桃子");
}
/**
* 思路:
* 其实就是求一串数中的最长递增数列
* @param peaches
* @return
*/
static int getMaxPeaches(int[] peaches) {
// 用于存储子序列的长度
int[] subSeqLen = new int[peaches.length];
for (int x=0; x<peaches.length; x++) {
subSeqLen[x] = 1; // 初始化最长子序列长度
for (int y=0; y<x; y++) { // 找出前x+1项最长的序列
if (peaches[x] > peaches[y] && subSeqLen[y]+1 > subSeqLen[x]) {
subSeqLen[x] = subSeqLen[y] + 1;
}
}
}
Arrays.sort(subSeqLen);
return subSeqLen[subSeqLen.length-1];
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: