需求
使用文字描述条形图的变化趋势
/**
* @author tao
* @ClassName CalculateTrends
* @description: 计算一个数组的变化趋势
* @datetime 2023年 03月 27日 13:40
* @version: 1.0
*/
public class CalculateTrends {
/**
* 连续上升
* @param nums
* @return
*/
public static int findLengthOfLCIS(List<Integer> nums) {
if(nums.size()<1){
return 0;
}
//存放所有的连续记录
List<Integer> all = new ArrayList<>();
int d = 0;
//最大的一个连续标识
int max = 1;
for(int i =1;i<nums.size();i++){
if(nums.get(i) > nums.get(i-1)){
max = Math.max(i - d + 1,max);
}else{
d = i;
}
if (nums.get(i) < nums.get(i-1)){
max = 1;
}
all.add(max);
}
return all.size() > 0 ? all.get(all.size()-1) : 0;
}
//连续下降
public static int findLengthOfDes(List<Integer> nums) {
if(nums.size()<1){
return 0;
}
//存放所有的连续记录
List<Integer> all = new ArrayList<>();
int d = 0;
int max = 1;
for(int i =1;i<nums.size();i++){
if(nums.get(i) < nums.get(i-1)){
max = Math.max(i - d + 1,max);
}else{
d = i;
}
if (nums.get(i) > nums.get(i-1)){
max = 1;
}
all.add(max);
}
return all.size() > 0 ? all.get(all.size()-1) : 0;
}
//连续平稳
public static int continuousSteady(List<Integer> nums) {
if(nums.size()<1){
return 0;
}
//存放所有的连续记录
List<Integer> all = new ArrayList<>();
int d = 0;
int max = 1;
for(int i =1;i<nums.size();i++){
if(nums.get(i) == nums.get(i-1)){
max = Math.max(i - d + 1,max);
}else{
d = i;
}
if (nums.get(i) != nums.get(i-1)){
max = 1;
}
all.add(max);
}
return all.size() > 0 ? all.get(all.size()-1) : 0;
}
/**
* 这里减一的原因市上面i初始化为1
* @param list
* @return
*/
public static Map<String, String> calculate(List<Integer> list){
HashMap<String, String> map = new HashMap<>();
int increase = findLengthOfLCIS(list);
int decline = findLengthOfDes(list);
int steady = continuousSteady(list);
if (steady > increase && steady > decline && steady-1 >= 3 ){
map.put("text","平稳");
map.put("continuation",String.valueOf(steady-1));
}
if (increase > decline && increase > steady && increase-1 >= 3){
map.put("text","上升");
map.put("continuation",String.valueOf(increase-1));
}
if (decline > increase && decline > steady && decline-1 >= 3){
map.put("text","下降");
map.put("continuation",String.valueOf(decline-1));
}
if (increase-1 < 3 && decline-1 < 3 && steady-1 <3){
map.put("text","波动");
map.put("continuation",null);
}
return map;
}
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(77, 45, 43,30,55,66,77,88,89,33,33,33,33,31,30,20);
System.out.println(integers.size());
System.out.println(CalculateTrends.calculate(integers));
}
}