【leetcode】121. Best Time to Buy and Sell Stock(c/c++,easy难度)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/81354402

原题链接  easy

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

我的代码

思路1:无脑写的话就是O(n2)的时间复杂度(提交测试时间372ms),买入时间i,卖出时间j,只要 i < j 且 prices[i] < prices[j]就会有利润prices[j]-prices[i],然后判断是否比最大利润max_p大就好了。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
         int len = prices.size();
         int buy_d,sell_d;
         int i,j,max_p=0;
         for(i = 0;i < len;i++){
             for(j = i + 1;j < len ; j++ ){
                if((prices[j] - prices[i]) > max_p){
                   max_p = (prices[j] - prices[i]);
                }

            }
         }
         return max_p;
    }
};

完整调试代码

//
// Created by maotianyi on 2018/8/1.
//

#include<iostream>
#include <cstdio>
#include <vector>
using namespace std;


int main(){
    vector<int> prices={7,1,5,3,6,4};
    int len = prices.size();
    int buy_d,sell_d;
    int i,j,max_p=0;
    for(i = 0;i < len;i++){
        for(j = i + 1;j < len ; j++ ){
            if((prices[j] - prices[i]) > max_p){
                   max_p = (prices[j] - prices[i]);
            }

        }
    }
    printf("%d",max_p);
    return 0;
}

思路2:求prices[i]后的最大值相减进行比较。但是提交之后不推荐。。虽然时间复杂度下去了,但是调用了std模版 更耗时了(runtime 1000+ms)

    int len = prices.size();
    int buy_d,sell_d;
    int i,j,max_p=0;
    for(i = 0;i < len - 1;i++){
        auto max_position = max_element(prices.begin()+i+1,prices.end());
        if((max_position - prices.begin()) > i && (*max_position - prices[i]) > max_p){
            max_p = *max_position - prices[i];
        }

    }

思路3:参考《——rumtime 4ms

        贪心法,选当前最优。遍历一次,更新当前最低价格和最高利润。

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/81354402
今日推荐