zoukankan      html  css  js  c++  java
  • [Leetcode 51] 122 Best Time to Buy and Sell Stock II

    Problem:

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

    Analysis:

    As we mentioned in "Best Time to Buy and Sell Stock" problem, every day make a transaction can get the knowledge of how much profit you can have on every day. Since here we are allowed to make as many transactions as we like, we just need to make those transactions with profit and ignore others. Then we can make sure that we have the max profit.

    Why this is right? Image you have three stock prices a, b, c

    if you buy at a and sell at c, then the profit is: c - a = c-b+b-a = (c-b)+(b-a). This means it equals you buy on day a and sell on day b, and then buy on day b and then sell on day c. This example illustrates the cumulative property of profit. Thus every transaction can be divided into multiple one-day transactions. If any one of the one-day transaction has negative profit, the final result is not max. We just remove it from the transaction. After removing all the negative-profit transactions, the result is max.

    Code:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (prices.size() == 0) return 0;
     7     
     8         int tP, sum;
     9         tP = 0;
    10         for (int i=0; i<prices.size()-1; i++) {
    11             sum = prices[i+1] - prices[i];
    12             if (sum > 0)
    13                 tP += sum;
    14         }
    15         
    16         return tP;
    17     }
    18 };
    View Code
  • 相关阅读:
    光脚丫学LINQ(025):如何验证DBML和外部映射文件
    使用LINQ to SQL将数据从一个数据库复制到另一个数据库
    用VS2010 C#写DLL文件并且调用(原创)
    linux初识
    Run Only One Copy Of Application
    SQL Server 2008开启远程连接
    用Visual C#做DLL文件
    SQL Server代理服务无法启动的处理方法(转载)
    QTP连接Oracle
    What's AJAX?
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099556.html
Copyright © 2011-2022 走看看