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 放低姿态
  • 相关阅读:
    [转载]服务器管理模块forever——Nodejs中间件系列
    [转载]NodeJS的异步编程风格
    break和continue的区别?
    JavaScript中遍历数组的方法
    行盒
    雪碧图
    将一个块级元素水平和垂直居中的方法
    Linux使用rdesktop连接Windows桌面
    git常用操作
    TiddlyWiki搭建个人博客
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5687367.html
Copyright © 2011-2022 走看看