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

      

  • 相关阅读:
    Sql的基础知识(一)
    Django--分页功能
    django--基础操作
    CSRF攻击与防御(转载)
    谈谈CSRF
    浅谈Dom遍历
    node50行代码实现壁纸爬取
    node解决request中文乱码问题
    数组去重方法(转载)
    淘宝dns解析错误导致首页打不开
  • 原文地址:https://www.cnblogs.com/LyningCoder/p/4209600.html
Copyright © 2011-2022 走看看