121_买卖股票的最佳时机

121_买卖股票的最佳时机

 

package 数组;

/**
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
 * 
 * @author Huangyujun
 *
 *         题意:其实就是买卖股票,我觉得低买高卖即可[找到当前两个数组元素之间相差的值最大]
 */
public class _121_买卖股票的最佳时机 {
    // 暴力法:超时
    // 找到价格最低点,在这之后剩余的找到价格最高的点
    // 算法:两层循坏需要优化【左右指针优化一下吧,需要考虑的是两个指针移动判断(不知道指针移动走向)~优化成二分查找算法】
//    public int maxProfit(int[] prices) {
//        int money = 0;
//        for(int i = 0; i < prices.length - 1; i++) {    //外层循坏买入股票
//            //一开始假设第一天买入
////            k = i;
//            for(int j = i + 1; j < prices.length; j++) {
//                int profit = prices[j] - prices[i];
//                if(profit > money) {
//                    money = profit;
//                }
//            }
//        }
//        return money;
//    }

    /**
     * 两次遍历太暴力了,超时了
     * 修改为一次遍历(在此遍历的过程中不断的更新找到最低点(最低点作为买点), 后续的非最低点,则考虑是否可以作为卖点)
     * @param prices
     * @return
     */
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

}

 

posted @ 2021-12-19 22:05  一乐乐  阅读(26)  评论(0编辑  收藏  举报