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

  

原文地址:https://www.cnblogs.com/LyningCoder/p/4209600.html