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

    Analyse: Since we can complete as much as transactions as we can, we can add a small interval as long as this interval is increasing. Specifically, we define the interval as neighbours. 

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size() <= 1) return 0;
     5     
     6         int result = 0;
     7         for(int i = 1; i < prices.size(); i++){
     8             if(prices[i] > prices[i - 1])
     9                 result += prices[i] - prices[i - 1];
    10         }
    11         return result;
    12     }
    13 };
  • 相关阅读:
    ssh 远程命令
    POJ 2287
    POJ 2376
    hihoCoder1488
    POJ1854
    HDU 5510
    HDU 4352
    CodeForces 55D
    HDU 1517
    CodeForces 1200F
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4743245.html
Copyright © 2011-2022 走看看