力扣刷题笔记17——股票的最大利润

股票的最大利润

问题

来自力扣

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
 

限制:
0 <= 数组长度 <= 10^5

我的代码


#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>
#include<queue>
#include <typeinfo>

 class Solution {
 public:
	 int maxProfit(vector<int>& prices) {
		 if (prices.size() <= 1) return 0;
		 for (int i = 0; i < prices.size()-1; ++i) {
			 prices[i] = *(max_element(prices.begin()+i+1, prices.end())) - prices[i];
		 }
		 prices[prices.size() - 1] = 0;
		 return *(max_element(prices.begin(), prices.end()));
	 }
 };
int main() {
	vector<int> prices = { 7,1,5,3,6,4 };
	vector<int> prices2 = { 7,6,4,3,1 };
	Solution mysolution;
	int s = mysolution.maxProfit(prices);
	int s2 = mysolution.maxProfit(prices2);
	cout << s<<"\t"<<s2;
	return 0;
}

我的做法是从按先后顺序,计算在每个节点买入股票后,能获得的最大收益,然后找出那个最大值。
感觉不太高效。因为我需要遍历每个节点后面的所有节点才能确认这个节点买入的收益。(如果思路不变,然后想提高效率,可以考虑每次保存的时候保存最大的值,然后算下一个节点的时候可以不用重新遍历。不过这种做法我想了下得从最后一个节点开始算。)

示例代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0){
            return 0;
        }
        int res = 0;
        for(int i = 0; i < prices.size() - 1; i++){
            for(int j = i + 1; j < prices.size(); j++){
                int maxprofit = prices[j] - prices[i];
                if(maxprofit <= 0){
                    break;
                }
                res = max(res, maxprofit);
            }
        }
        return res;
    }
};

示例代码的做法是计算在每个节点卖出的利润。然后它记住了前面i-1个点中的最大值,所以在算第i个点时,不需要重新遍历,节省了时间消耗。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小欣CZX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值