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 };
  • 相关阅读:
    magento head.phtml 加载<a target=_parent
    火狐浏览器七个黑客必备工具插件
    Windows 2003】利用域&&组策略自动部署软件
    js zhi网马
    js 判断网页类型
    zencart hosts本地解析
    优化之zencart第一时间修改原始内容
    realypay
    mysql 配置
    1.4-动态路由协议OSPF③
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646392.html
Copyright © 2011-2022 走看看