给出一个数组,返回它的最大值和最小值。

本文介绍了一种简单的买卖策略,旨在通过找到最低购买价和最高销售价来实现利润最大化。文章提供了一个实用的Java代码示例,展示了如何从给定的数组中找出最小值和最大值,从而为买卖决策提供数据支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

Ben has a very simple idea to make some profit: he buys something and sells it again. Of course, this wouldn't give him any profit at all if he was simply to buy and sell it at the same price. Instead, he's going to buy it for the lowest possible price and sell it at the highest.

Task

Write a function that returns both the minimum and maximum number of the given list/array.

Examples

MinMax.minMax(new int[]{1,2,3,4,5}) == {1,5}
MinMax.minMax(new int[]{2334454,5}) == {5, 2334454}
MinMax.minMax(new int[]{1}) == {1, 1}

 代码:


import java.util.Arrays;


public class MinMax {
    //方法一
    public static int[] minMax(int[] arr) {
        int[] b=new int[2];
        if(arr.length==1){
            System.arraycopy(arr,0,b,0,1);
            System.arraycopy(arr,0,b,1,1);
        }
        if(arr.length==2){
            if(arr[0]<arr[1]){
                System.arraycopy(arr,0,b,0,2);
            }else {
                System.arraycopy(arr,1,b,0,1);
                System.arraycopy(arr,0,b,1,1);
            }
        }
        if(arr.length>2){
            for(int k=0;k<arr.length-1;k++){
                for(int j=0;j<arr.length-k-1;j++){
                    if(arr[j]>arr[j+1]){
                        int t=arr[j+1];
                        arr[j+1]=arr[j];
                        arr[j]=t;
                    }
                }
            }
            System.arraycopy(arr,0,b,0,1);
            System.arraycopy(arr,arr.length-1,b,1,1);
        }
        return b;
    }
    
    //方法二
    public static int[] minMax2(int[] arr) {
        Arrays.sort(arr);
        return new int[]{arr[0],arr[arr.length-1]};
    }
    
    public static void main(String[] args) {
//        int[] b={1};
        int[] b={10,2,20,100};
        System.out.println(Arrays.toString(minMax(b)));
        System.out.println(Arrays.toString(minMax2(b)));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值