zoukankan      html  css  js  c++  java
  • 【leetcode】Best Time to Buy and Sell Stock II

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

    其核心就是找到所有的单调递增区间,然后卖出去
     
    最简单的,每当有涨价,就卖出去,累加所有收益(Accept了,不过似乎 buy one and sell one share of the stock multiple times了)
     
     
     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         
     5         int profit=0;
     6         for(int i=1;i<prices.size();i++)
     7         {
     8             if(prices[i]>prices[i-1])
     9             {
    10                 profit+=prices[i]-prices[i-1];
    11             }
    12         }
    13         return profit;
    14         
    15     }
    16 };

     

     
    下面代码找到了递增的区间,然后在最后一天卖出
     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4        
     5        
     6         int profit=0;
     7         int n=prices.size();
     8        
     9         if(n==0)
    10         {
    11             return 0;
    12         }
    13         int buyPrice=prices[0];
    14        
    15         for(int i=1;i<n;i++)
    16         {
    17             if(prices[i]<prices[i-1])
    18             {
    19                 profit+=prices[i-1]-buyPrice;
    20                 buyPrice=prices[i];
    21             }
    22         }
    23        
    24         profit+=prices[n-1]-buyPrice;
    25        
    26         return profit;
    27        
    28     }
    29 };
     
     
  • 相关阅读:
    hdu 5171(矩阵快速幂,递推)
    hdu 1316(大整数)
    hdu 5170(数学)
    hdu 5167(dfs)
    hdu 5166(水题)
    hdu 5720(贪心+区间合并)
    BestCoder 2nd Anniversary的前两题
    hdu 3065(AC自动机)
    2.3绘制构造线与射线
    查找ARP攻击源
  • 原文地址:https://www.cnblogs.com/reachteam/p/4194488.html
Copyright © 2011-2022 走看看