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

    Solution: 1. At the beginning of the ascending order: buy.
    At the ending of the ascending order: sell.
    2. For ascending order [1,2,4], (4 - 1) == (2 - 1) + (4 - 2).

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         if(prices.size() <= 1) {
     5             return 0;
     6         }
     7         int profit = 0;
     8         int start = 0, end = 0;
     9         for(int i = 1; i < prices.size(); i++) {
    10             if(prices[i] < prices[i-1]) {
    11                 profit += prices[end] - prices[start];
    12                 start = i;
    13                 end = i;
    14             }
    15             else {
    16                 end = i;
    17             }
    18         }
    19         profit += prices[end] - prices[start];
    20         return profit;
    21     }
    22 
    23     int maxProfit_2(vector<int> &prices) {
    24         int res = 0;
    25         for (int i = 1; i < prices.size(); ++i)
    26             if (prices[i] > prices[i-1])
    27                 res += prices[i] - prices[i-1];
    28         return res;
    29     }
    30 };
  • 相关阅读:
    hdoj5813【构造】
    Codeforces645B【树状数组求逆序数】
    pojcoin【未完待续】
    hdoj5818【模拟】
    poj2385【基础DP】
    poj3069【贪心,水】
    谦虚
    poj3617【贪心】
    poj2229【完全背包-规律Orz...】
    poj3176【简单DP】
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646392.html
Copyright © 2011-2022 走看看