121-Best Time to Buy and Sell Stock

本文介绍了一个简单的算法,用于解决股票交易中寻找最佳买卖时机的问题。该算法通过一次遍历股票价格数组并维护最低购买价格来确定最大利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类别:dynamic programmin
难度:easy

题目描述

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/

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.
这里写图片描述
(买入的时间必须要比卖出的时间早,即后面的数字要比前面的大)

算法分析

只需要遍历数组,维护一个最小价格,每到一个价格的时候,比较当前能够获得的最大利益(即当前价格减去最小价格),将当前的最大利益与之前已经得到的最大利益进行比较取最大值。
比较简单,理解即可实现。

代码实现

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

//  cur - min = curmax
//  max(max, curmax)
int maxProfit(vector<int>& prices) {
    int minPrice = 10000;
    int n = prices.size();
    int result = 0;
    for (int i = 0; i < n; ++i) {
        minPrice = (minPrice < prices[i]) ? minPrice : prices[i];
        result = (prices[i] - minPrice) > result ? prices[i] - minPrice : result;
    }
    return result;
}
int main() {
    int n;
    int num;
    vector<int> data;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> num;
        data.push_back(num);
    }
    cout << maxProfit(data) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值