zoukankan      html  css  js  c++  java
  • leetcode| Best Time to Buy and Sell Stock II

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    题目:题目的意思有点难理解,借助有道词典,我理解的意思是:给出一个数组,数组的下标是日期,i表示第i天,里面的元素表示该天股票的价格,问你怎么选择时间节点买入卖出才能受益最大,算出最大收益

    思路:这个题目的提示关键词有一个 Greedy,同样是有道后知道这个是贪心的意思,而后知道这个是专业术语叫贪心算法,大概意思是,不管之后的情况,只考虑当前状态的处理最佳就行,十分之符合现实,因为今天之后的股票价格走势散户们哪里知道啊,今天之前的是可以知道的。。。题目出的很现实,代码实现我们也是这样处理的,只要今天比昨天价格高,我们就买,之后价格多高不管,一言蔽之,见好就收

    public int maxProfit(int[] prices) {
      int res = 0,len = prices.length,price = 0;
       for(int i = 0;i<len-1;i++){
        price = prices[i+1]-prices[i];
        if(price>0){
          res+=price;
        }
        }
        return res;
      }

    StayHungry 求知若渴 StayFoolish 放低姿态
  • 相关阅读:
    Struts2异常处理配置
    struts2支持的结果类型
    Project facet Java 1.8 is not supported by target runtime Apache Tomcat v7.0.
    net.paoding.analysis.exception.PaodingAnalysisException: dic home should not be a file, but a directory!
    struts.xml路径修改后的web配置
    struts.xml中的配置常量的含义
    Spring实战笔记
    2018第2周日
    新人替代旧人
    Web安全总结摘录
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5687367.html
Copyright © 2011-2022 走看看