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 };
  • 相关阅读:
    LeetCode
    数据流中的中位数
    二叉搜索树的第k个结点
    对称的二叉树
    按之字形顺序打印二叉树
    把二叉树打印成多行
    二叉树的下一个结点
    链表中环的入口结点
    删除链表中重复的结点
    不用加减乘除做加法
  • 原文地址:https://www.cnblogs.com/chkkch/p/2757533.html
Copyright © 2011-2022 走看看