zoukankan      html  css  js  c++  java
  • *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).

    题解:

    简单的方法就是一旦第二天的价格比前一天的高,就在前一天买入第二天卖出。代码如下:

     1 public int maxProfit(int[] prices) {
     2     int total = 0;
     3     for (int i=1; i< prices.length; i++) {
     4         if (prices[i]>prices[i-1]){ 
     5             int profit = prices[i]-prices[i-1];
     6             total += profit;
     7         }
     8     }
     9     return total;
    10     }

    但是这个会违反“不能同一天买卖的规则”,例如3天的价格分别为1,2,3,那么按上述算法就会在2那天同一天买卖了。。。

     正确的做法是: 第1天买第3天卖。

     虽然两种方法数字结果是对的,但是逻辑不一样。。

     不过虽然这么说,这道题的本事仍然是让你找最大利润,并没有让你明确哪天买哪天卖。

     所以对面试官你仍然可以说,这种方法只是帮助我找到最大利润,我并没有说是要在同一天买卖,只是计算:所有第二天比前一天大的差值的合,我是为了找最大利润而已(画个趋势图讲解一下就行了。。)。

    不过如果不是那样略有点投机取巧的话,干嘛非要每一次有一点点增长就加总和,带来不必要的解释麻烦?

    何不先找到递减的局部最低点,再找到递增的局部最高点,算一次加和,然后再这么找? 这样就能保证买卖不会在同一天了。。

    代码如下:

     1 public static int maxProfit(int[] prices) {
     2         int len = prices.length;
     3         if(len <= 1)
     4             return 0;
     5         
     6         int i = 0;
     7         int total = 0;
     8         while(i < len - 1){
     9             int buy,sell;
    10             //寻找递减区间的最后一个值(局部最小点)
    11             while(i+1 < len && prices[i+1] < prices[i])
    12                 i++;
    13             //局部最小点作为买入点
    14             buy = i;
    15             
    16             //找下一个点(卖出点至少为下一个点)
    17             i++;
    18             //不满足。。继续往下找递增区间的最后一个值(局部最高点)
    19             while(i<len && prices[i] >= prices[i-1])
    20                 i++;
    21             //设置卖出点
    22             sell = i-1;
    23             //计算总和
    24             total += prices[sell] - prices[buy];
    25         }
    26         return total;
    27     }

    reference: 

    http://www.cnblogs.com/springfor/p/3877065.html

    http://www.cnblogs.com/TenosDoIt/p/3436457.html

  • 相关阅读:
    nyoj 164&amp;&amp;poj2084 Game of Connections 【卡特兰】
    1、Cocos2dx 3.0游戏开发找小三之前言篇
    hibernate一级缓存,二级缓存和查询缓存
    WCF服务端调用client.
    优化中的subgradient方法
    Xsolla和Crytek合作,对游戏战争前线推出全新支付方式
    CNZZ站点流量统计原理简析
    分数加减法
    【jvm】windows下查看java进程下多线程的相关信息
    【面试 docker+k8s+jenkins】【第二十篇】docker+k8s+jenkins相关面试
  • 原文地址:https://www.cnblogs.com/hygeia/p/4641615.html
Copyright © 2011-2022 走看看