zoukankan      html  css  js  c++  java
  • [LeetCode] Best Time to Buy and Sell Stock 2

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

    这道题就是找到最多的递增子序列个数,然后把利润加总。

     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)
     7             return 0;
     8             
     9         int start = prices[0];
    10         int profit = 0;
    11         for(int i = 1; i < prices.size(); i++)
    12         {
    13             if (prices[i] >= prices[i-1])
    14                 continue;
    15                 
    16             profit += prices[i-1] - start;
    17             
    18             start = prices[i];
    19         }
    20         
    21         profit += prices[prices.size()-1] - start;
    22         
    23         return profit;
    24     }
    25 };
  • 相关阅读:
    oracle备份表和数据
    sql 替换字段中的部分字符,替换指定字符
    前端MVVM框架
    学习Bootstrap
    oracle 取前10条记录
    sql时间比较
    vlookup函数的使用
    树的遍历
    Java数据结构和算法(四)——栈
    面试大全之JVM篇
  • 原文地址:https://www.cnblogs.com/chkkch/p/2757533.html
Copyright © 2011-2022 走看看