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
  • 相关阅读:
    Webpack实现按需打包Lodash的几种方法详解
    一文带你了解babel-preset-env
    Vue-给对象新增属性(使用Vue.$set())
    vue v-slot
    Vue2.4+新增属性.sync、$attrs、$listeners
    彻底搞定Javascript事件循环
    Spring Boot 添加JSP支持【转】
    防火墙设置
    黑黑客客
    tomcat启动时设定环境变量
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099556.html
Copyright © 2011-2022 走看看