Best Time to Buy and Sell Stock

(onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

注意: 限制条件: 先买后卖(不同天)。

思想: 买了后,1. 若以后价格不变,不买不卖。 1. 更价格低,重新买。2. 价格升高,假定抛售,更新一下利润值。

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int> &prices) {
  4. int buy = 0x7fffffff, maxProfile = 0;
  5. for(int i = 0; i < prices.size(); ++i) {
  6. if(prices[i] == buy) continue;
  7. if(prices[i] < buy) { buy = prices[i]; continue; }
  8. else maxProfile = max(maxProfile, prices[i]-buy);
  9. }
  10. return maxProfile;
  11. }
  12. };

Best Time to Buy and Sell Stock II

(onlineJudge:https://oj.leetcode.com/problems/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).

思想:求出所有非递减序列两端绝对值之和。我贴在 leedcode 的代码和证明:

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int> &prices) {
  4. int n = prices.size();
  5. if(n == 0) return 0;
  6. int start = 0, profile = 0;
  7. for(int i = 1; i < n; ++i) {
  8. if(prices[i] < prices[i-1]) {
  9. profile += prices[i-1] - prices[start];
  10. start = i;
  11. }
  12. }
  13. profile += prices[n-1] - prices[start];
  14. return profile;
  15. }
  16. };
  17. /*********************** *provement ***************/
  18. /*Explain the code I pasted above:
  19.  
  20. From left to right I find out every subsequence that not exist decrease.
  21.  
  22. such as: l ... k1 ...k2 ... h (l <=...<= k1 <= ... k2 <= ... <= h)
  23.  
  24. In this sequence: ( k1-l ) + ( h-k2 ) = ( h-l ) - ( k2-k1 ) <= ( h-l );
  25.  
  26. So (h - l) will be the maximum profit in this days.
  27.  
  28. Another case:
  29.  
  30. L1 ...d1... H1 K2 ...k... K3 L2 ...d2... H2 (L1 <=... H1 > K2 >=...k >=... K3 > L2 <=... H2 )
  31.  
  32. K2 ... K3 is not exist increase sequence.
  33.  
  34. then for any k in that position,
  35.  
  36. ( k-d1 ) + ( d2-k ) <= ( K2-L1 ) + ( H2-K3 ) < ( H1-L1 ) + ( H2-L2 )
  37.  
  38. In my code, variant "start" is the start of every no decrease sequence.*/

A little Adjustment.

  1. class Solution {
  2. public:
  3. int maxProfit(vector<int> &prices) {
  4. int start = 0, profile = 0;
  5. for(size_t i = start+1; i < prices.size(); ++i) {
  6. if(prices[i] < prices[i-1]) {
  7. profile += prices[i-1] - prices[start];
  8. start = i;
  9. }
  10. else if(i+1 == prices.size())
  11. profile += prices[i] - prices[start];
  12. }
  13. return profile;
  14. }
  15. };

Best Time to Buy and Sell Stock III

(onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

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 at most two transactions.

Note: 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. vector<int> preProfile(prices.size()+2, 0), postProfile(prices.size()+2, 0);
  5.  
  6. int minPrice = 0x7fffffff;
  7. for(size_t i = 1; i <= prices.size(); ++i) {
  8. minPrice = min(minPrice, prices[i-1]);
  9. preProfile[i] = max(prices[i-1] - minPrice, preProfile[i-1]);
  10. }
  11.  
  12. int maxPrice = 0;
  13. for(int i = prices.size(); i >= 1; --i) {
  14. maxPrice = max(maxPrice, prices[i-1]);
  15. postProfile[i] = max(maxPrice - prices[i-1], postProfile[i+1]);
  16. }
  17.  
  18. int maxProfile = 0;
  19. for(size_t i = 1; i <= prices.size(); ++i)
  20. maxProfile = max(maxProfile, preProfile[i] + postProfile[i]);
  21. return maxProfile;
  22. }
  23. };

27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III的更多相关文章

  1. [Swift]LeetCode122. 买卖股票的最佳时机 II | 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 al ...

  2. [Leetcode 122]买股票II 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 ...

  3. [LeetCode 122] - 买入与卖出股票的最佳时机II(Best Time to Buy and Sell Stock II)

    问题 假设你有一个数组,其中的第i个元素表示一只股票在第i天的价格. 设计一个算法找出最大的利润值.你可以进行任意多次的交易(即多次的卖出并买入一份股票).你不能在同一时间进行多次交易(即你必须在再次 ...

  4. [LeetCode] Best Time to Buy and Sell Stock with Cooldown 买股票的最佳时间含冷冻期

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  5. [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  6. [LeetCode] Best Time to Buy and Sell Stock III 买股票的最佳时间之三

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  7. Best Time to Buy and Sell Stock with Cooldown

    Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...

  8. LEETCODE —— Best Time to Buy and Sell Stock II [贪心算法]

    Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price of a ...

  9. Best Time to Buy and Sell Stock系列

    I题 Say you have an array for which the ith element is the price of a given stock on day i. If you we ...

随机推荐

  1. iOS iPad开发之UIPopoverController的使用

    1. 什么是UIPopoverController? 是iPad开发中常见的一种控制器(在iphone上不允许使用) 跟其他控制器不一样的是,它直接继承自NSObject,并非继承自UIViewCon ...

  2. Rhel6-torque作业调度系统配置文档

    系统环境: rhel6 x86_64 iptables and selinux disabled 主机: 192.168.122.121 server21.example.com 计算节点 192.1 ...

  3. C#学习笔记----枚举、结构、方法及构造函数的总结

    一.枚举 语法: [public] enum 枚举名 { 值1, 值2, 值3, ........ } public:访问修饰符.公开的公共的,哪都可以访问. enum:关键字,声明枚举的关键字 枚举 ...

  4. Cache-control使用Cache-control:private学习笔记

    其作用根据不同的重新浏览方式,分为以下几种情况:(1).打开新窗口值为private.no-cache.must-revalidate,那么打开新窗口访问时都会重新访问服务器.而如果指定了max-ag ...

  5. 绑定hosts

    测试过程中需绑定hosts.将测试环境IP绑定域名,输入域名即可连接到测试环境. 1  hosts文件地址:C:\WINDOWS\system32\drivers\etc 2  用记事本打开hosts ...

  6. 分析器错误 MvcApplication 找不到

    <%@ Application Codebehind="Global.asax.cs" Inherits="test.MvcApplication" La ...

  7. [深入Python]__new__和__init__

    class A(object): def __init__(self): print "init" def __new__(cls,*args, **kwargs): print ...

  8. cocos2dx 3.8版关于#include "GB2ShapeCache-x.h"

    关于coco2d-x 3.8版的PhysicsEditor.exe1.09版的GB2ShapeCache-x.h.cpp中有些方法更新了和容器的使用方法,还有就是头文件include "CC ...

  9. Python OpenCV —— Arithmetic

    图案的算术操作. # -*- coding: utf-8 -*- """ Created on Wed Sep 28 11:54:47 2016 @author: Adm ...

  10. 回顾Spring框架

    Spring框架: 传统JavaEE解决企业级应用问题时的"重量级"架构体系,使它的开发效率,开发难度和实际的性能都令人失望.Spring是以一个 救世主的身份降临在广大的程序员面 ...