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

    题目:

    Say you have an array for which the i th 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天的价格。交易次数不限,但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。

    分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。所有增量和就是最大利润

    这道题由于可以无限次买入和卖出。我们都知道炒股想挣钱当然是低价买入高价抛出,那么这里我们只需要从第二天开始,如果当前价格比之前价格高,则把差值加入利润中,因为我们可以昨天买入,今日卖出,若明日价更高的话,还可以今日买入,明日再抛出,明天价钱低了则今天不买,明天再买因为此时明天买后天卖比今天买后天卖赚得多。以此类推,遍历完整个数组后即可求得最大利润。

    为什么是看明天价格和今天价格,而不是今天买后面几天再卖。这是因为,如果后天价格比明天高,那么跟今天买明天卖,然后明天又买,后天卖一个意思;如果后天价格比明天低,那么很明显,明天就该卖出了,这样利润大,然后明天不买了,后天再买,赚得多。

    代码:

    public class Solution {
      public int maxProfit(int[] prices) {
        if(prices==null||prices.length==0)
          return 0;
        //所有增量和就是最大利润
        int sum=0;
        for(int i=1;i<prices.length;i++){
          if(prices[i]>prices[i-1])
            sum+=prices[i]-prices[i-1];
          }
        return sum;
      }
    }

  • 相关阅读:
    201571030134 由《构建之法》所想到的~
    unity3d 打包Xcode工程自动添加framework
    Unity3d Vuforia与Mobile Movie Texture插件结合
    Unity3d 打开本地摄像头扫描二维码
    Unity3d 获取文件夹的图片
    iOS开发 Button自定义
    Unity3D判断鼠标左右滑动
    unity3d控制物体旋转的角度
    第一次作业
    人工智能第二次作业
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8029951.html
Copyright © 2011-2022 走看看