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

      

  • 相关阅读:
    【t083】买票
    基于Linux应用层的6LOWPAN物联网网关及实现方法
    Express的路由详解
    day18 8.jdbc中设置事务隔离级别
    day18-事务与连接池 6.事务隔离级别与解决问题
    day36-hibernate检索和优化 02-Hibernate检索方式:简单查询及别名查询
    day37-hibernate 02-Hibernate二级缓存:二级缓存的散装数据
    day36-hibernate检索和优化 01-上次课内容回顾
    day36-hibernate检索和优化 05-Hibernate检索方式:离线条件查询
    SQL Server 涉及数据库安全常用SQL语句
  • 原文地址:https://www.cnblogs.com/LyningCoder/p/4209600.html
Copyright © 2020-2023  润新知