zoukankan      html  css  js  c++  java
  • 面试题38:股票最大收益问题

    leetcode中股票问题指的是股票的价格处于波动当中,分别在最多购买一次、买卖任意多次、买卖k次的最大收益

    Say you have an array for which the ithelement 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 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         int res = 0;
     5         int buy = INT_MAX;
     6         for(int price : prices){
     7             buy = min(buy,price);
     8             res = max(res,price-buy);
     9         }
    10         return res;
    11     }
    12 };

    Say you have an array for which the ithelement 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 sum = 0;
     5         for(size_t i =1;i<prices.size();i++){
     6             if(prices[i] > prices[i-1]){
     7                 sum += prices[i] - prices[i-1];
     8             }
     9         }
    10         return sum;
    11     }
    12 };

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

    Design an algorithm to find the maximum profit. You may complete at most twotransactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int n = prices.size();
            if(n < 2) return 0;
            vector<vector<int>> g(n,vector<int>(3,0));
            vector<vector<int>> l(n,vector<int>(3,0));
            for(int i=1;i<n;i++){
                int diff = prices[i] - prices[i-1];
                for(int j=1;j<=2;j++){
                    l[i][j] = max(g[i-1][j-1] +max(diff,0),l[i-1][j] + diff);
                    g[i][j] = max(g[i-1][j],l[i][j]);
                }
            }
            return g[n-1][2];
        }
    };
  • 相关阅读:
    script:查看历史sql执行信息
    爱在watir(1)----一切从搭讪开始
    最简单的视音频播放演示样例7:SDL2播放RGB/YUV
    Git flow的分支模型与及经常使用命令简单介绍
    操作系统开发之——打开A20
    阿牛的EOF牛肉串-记忆化搜索或动态规划
    LintCode-Copy Books
    Android:Unable to resolve target ‘android-8’问题解决
    编程规范(一 之kmalloc,fflush,fclose,char_init)
    androidannotations的background和UiThread配合使用參考
  • 原文地址:https://www.cnblogs.com/wxquare/p/6944069.html
Copyright © 2011-2022 走看看