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

     题意:可以做多次交易,但必须是做完一次交易了,再做下一次。

    思路:这个要注意和显示生活中区别,这里是每天股票的价格已经知道了,所以,买卖的时候,只要是盈利的都做。大致过程是,对相邻两天的股票价格比较,只要后者大于前者,这次买卖就做。代码如下:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) 
     4     {
     5         int profit=0;
     6         int len=prices.size();
     7         for(int i=0;i<len-1;++i)
     8         {
     9             if(prices[i+1]-prices[i]>0)
    10                 profit+=prices[i+1]-prices[i];
    11         }    
    12         return profit;
    13     }
    14 };

    这里值得注意的是:若代码中第6、7两行写成如下形式,是不能AC的。个人认为是prices.size()的类型为vector<int>::size_type,而减1以后,在prices.size()=0的情况,会负溢出。导致i小于一个正整数,但是数组中没有值,对数组进行访问时,会发生段问题。

    (自己的考虑,没有考虑到类型限制,详情见下面)

    1 for(int i=0;i<prices.size()-1;++i)
    2 {
    3     ......
    4 }

    在本地验证的代码:

     1 #include<iostream>
     2 #include<vector>
     3 
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     vector<int> a ;
     9     cout << a.size() - 1 << endl;
    10     return 0;
    11 }
    12 
    13 //输出42949647295

    解决的方法:一、之前加if判断,二、使用最上面代码中的那种方式--先求数组大小,然后用这个值去参与for循环。

    //更新

    这里给出Grandyang的回答:因为prices.size()返回的是size_type型的,这是一种unsigned类型,也就是无符号类型,所以在直接对其做减法是不行的,因为负数对其来说不合法,所以我们可以先强制将其转为整型,再做法,比如:

    1 for(int i = 0; i < (int)prices.size() - 1; ++i)
    2 {
    3     ......
    4 }

    (感谢Grandyang!!!)

  • 相关阅读:
    Tomcat
    DOM/SAX/PULL解析XML
    Android网络编程 知识框架
    Chapter 10 Networking/JSON Services
    Chapter 10 Networking/Web Service Using HTTP
    Android-Universal-Image-Loader
    8.Media and Camera/Media Camera
    PAT乙级1007.素数对猜想(20)
    筛法求素数详解
    PAT乙级1006.换个格式输出整数(15)
  • 原文地址:https://www.cnblogs.com/love-yh/p/7095340.html
Copyright © 2011-2022 走看看