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

    leetCode 122 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).

    120是说只能买卖一次,这个题是可以买卖多次,第二次买之前一定要先卖出一次。 

    题解:

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

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         int n=prices.length;
     4          if(n<=1)return 0;
     5          int max=0;
     6          for(int i=1;i<prices.length;i++)
     7          {
     8              if(prices[i]>prices[i-1])
     9                  max+=prices[i]-prices[i-1];
    10          }
    11          return max;
    12     }
    13 }
    View Code

    之前提交成功的一个版本。

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

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

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

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

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

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

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

    所以下边这个方法是找第一个递减区间最低值,然后再找第一个递增区间的最高值,做一个买入和卖出。一直到最后。

    代码如下:

     1 public class Solution {
     2     //http://www.cnblogs.com/springfor/p/3877065.html
     3     //找每一个增长区间和递减区间。
     4     public int maxProfit(int[] prices) {
     5         int len = prices.length;
     6         if(len <= 1) return 0;
     7         
     8         int buy;
     9         int sell;
    10         int i = 0;
    11         int total = 0;
    12         while(i < len-1){
    13             while(i+1 < len && prices[i] > prices[i+1])
    14             i++;
    15             buy = i;
    16             i++;
    17             while(i < len && prices[i] > prices[i-1])
    18             i++;
    19             sell =  i-1;
    20             total +=prices[sell]-prices[buy];
    21         }
    22         return total;
    23     }
    24 }

    上边标注了,引用来源。

  • 相关阅读:
    iOS 新建xib文件时,最外层view的约束问题
    React native 无法弹出调试控件的问题
    从GitHub下载demo时遇到的依赖问题
    Mac 解决 Sourcetree 同步代码总需要密码的问题
    Mac 安装JRE 1.8
    正则表达式-- (.*?) 或 (.*+)
    字符串内有多个#号,每俩#号为一组,JavaScript 截取每组#号之间的字符
    Js/jQuery实时监听input输入框值变化
    Redis设置密码
    redis本机能访问 远程不能访问的问题
  • 原文地址:https://www.cnblogs.com/hewx/p/4532761.html
Copyright © 2011-2022 走看看