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 };
  • 相关阅读:
    XJOI网上同步训练DAY2 T2
    XJOI网上同步训练DAY2 T1
    BZOJ 2661 连连看
    HDU 4411 Arrest
    BZOJ 2324 营救皮卡丘
    BZOJ 1927 星际竞速
    BZOJ 3550 Vacation
    XJOI网上同步训练DAY1 T3
    php 类的相互访问
    ThinkPhp5.0_文件上传
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4921999.html
Copyright © 2011-2022 走看看