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;
    }
    

      

  • 相关阅读:
    Fragment学习简介与生命周期研究
    POJ 2513 Colored Sticks 【Trie树】
    listView实时更新
    苹果技术支持联系方式
    文件中随机读取行问题
    hdu 4554
    hdu 4556
    离开通讯后就职互联网行业的一些感悟
    HDU1016:Prime Ring Problem
    dbgrideh通用打印
  • 原文地址:https://www.cnblogs.com/LyningCoder/p/4209600.html
Copyright © 2011-2022 走看看