zoukankan      html  css  js  c++  java
  • LeetCode OJ:Best Time to Buy and Sell Stock II(股票买入卖出最佳实际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).
    对贪心不是很了解,这题跟上一个类似的题目相差还是有点大的,没想出来,看了别人的实现。实际上思路很简单,只要一直在涨就不动,一旦发现跌了之后就将前一个值记录下来之后求出与买入时候的差值,重复进行下一轮的买入以及卖出,代码如下:

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         int sz = prices.size();
     5         if(!sz) return 0;
     6         int profit = 0;
     7         int start = 0;
     8         for(int i = 1; i < sz; ++i){
     9             if(prices[i] >= prices[i - 1])
    10                 continue;
    11             profit += prices[i - 1] - prices[start];
    12             start = i;
    13         }
    14         profit += prices[sz - 1] - prices[start];
    15         return profit;
    16     }
    17 };
  • 相关阅读:
    接口问题
    鉴权 授权 验签
    adb常用命令
    cookie session
    常见http返回状态码
    Linux下mysql数据库的命令
    Linux课堂笔记--第九天
    Linux课堂随笔 -第八天
    Linux课堂笔记-第七天
    Linux课堂随笔-第六天
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4921999.html
Copyright © 2011-2022 走看看