zoukankan      html  css  js  c++  java
  • leetcode-121-买卖股票的最佳时机

    问题:

    可以将问题转化为如下图所示,即求多个累计的收入差

    分析:

    如果当前位置i的价格比i+1的价格高,则当前不是买入点,则继续判断下一个位置,

    如果当前位置i的价格比i+1的价格低,并且i+1仍比i+1+1低,则在当前位置买入,知道i+n比i+n+1大时,卖出。

    继续下一轮判断

    package com.example.demo;
    
    public class Test121 {
    
        /**
         * 多个
         *
         * @param prices
         * @return
         */
        public int maxProfit(int[] prices) {
            if (prices == null || prices.length == 0) {
                return 0;
            }
            int cur = 0;
            int vally = prices[0];
            int peak = 0;
            int income = 0;
            while (cur < prices.length - 1) {
                //找到卖出点,谷底
                while (cur < prices.length - 1 && prices[cur] >= prices[cur + 1]) {
                    cur++;
                }
                vally = prices[cur];
                //找到比当前大的值(即最高点,顶峰)
                while (cur < prices.length - 1 && prices[cur] <= prices[cur + 1]) {
                    cur++;
                }
                peak = prices[cur];
                income += peak - vally;
                //如果此时cur仍然没有到最后,则进行再一次循环
            }
            return income;
        }
    
        public static void main(String[] args) {
            Test121 t = new Test121();
            int[] arr = {7, 1, 5, 3, 6, 4};
            int i = t.maxProfit(arr);
            System.out.println(i);
        }
    }
  • 相关阅读:
    简约 高效 基层管理体制
    六大纪律
    平行文
    党章
    四大考验 四大危险
    创新、协调、绿色、开放、共享五大发展理念
    微信公众号-->微信html页面缓存问题
    本地kafka环境部署
    >>读懂一本书:樊登读书法>>-->摘抄
    海龟交易法则(第3版)-->摘抄
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11265472.html
Copyright © 2011-2022 走看看