zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock

    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 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.

    solution

    min记录最小买入价

    maxProfit记录最大利润

    遍历array,不断更新最小买入价,计算更新最大利润

    #include<iostream>
    #include<stdlib.h>
    #include<time.h>
    using namespace std;
    
    int price[10]={0};
    int maxProfit(int price[], int n)
    {
        int minu = RAND_MAX;
        int maxn = 0;
        for(int i = 0; i < n; i++){
            minu = price[i] < minu ? price[i] : minu;
            maxn = (price[i] - minu) > maxn ? (price[i] - minu) : maxn;
        }
        return maxn;
    }
    
    int main()
    {
        int n = sizeof(price)/sizeof(int);
        srand((unsigned)time(NULL));
        for(int i = 0; i < n; i++) {
            price[i]=rand()%1000;
        }
        int pro =  maxProfit(price, n);
        for(int i = 0; i < n; i++) {
            cout << price[i] << "	";
        }
        cout << endl;
        cout << "the max profit is :" << pro << endl;
        return 0;
    }
    

     Best Time to Buy and Sell Stock II

    Question Solution
    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).

    解:
    既然要最大化利润,我们应该拿下股票所有的升值部分。从开始到最后股票可能有升有降,那么,我们把每一个升值的区间的利润加在一起就是最大值。

    也就是每次比较当天和前一天的股票值,如果是上升,就加上这个差值即可。

    #include<iostream>
    #include<stdlib.h>
    #include<time.h>
    using namespace std;
    
    int price[10] = {0};
    
    int maxProfit(int price[], int n)
    {
        int maxPro = 0;
        for (int i = 1; i < n ; i++) {
            int diff = price[i] - price[i -1];
            if (diff > 0) {
                maxPro += diff;
            }
        }
        return maxPro;
    }
    
    
    int main()
    {
        int n = sizeof(price)/sizeof(int);
        srand((unsigned)time(NULL));
        for(int i = 0; i < n; i++) {
            price[i] = rand()%1000;
        }
        int pro = maxProfit(price, n);
        cout << pro << endl;
    
        return 0;
    }
    

      

  • 相关阅读:
    manacher(马拉车)算法详解+例题一道【bzoj3790】【神奇项链】
    【bzoj2160】【啦啦队排练】manacher(马拉车)+差分+快速幂
    file.seek()
    python strip() 函数探究
    vscode配置python环境
    关于ubuntu16.04系统无法系统更新的解决
    汇率计算器
    pythno学习小结-替换python字典中的key值
    python学习小结-字典key,val互换
    python学习笔记(7)——集合(set)
  • 原文地址:https://www.cnblogs.com/LyningCoder/p/4209600.html
Copyright © 2011-2022 走看看