leetcode-121. Best Time to Buy and Sell Stock

问题描述

假设给定一个数组,第i个元素表示第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 (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.

思路

思路是看评论区的,通过比较当前元素与历史最低的价格,得到这一天卖出股票后得到的利润,然后比较历史最大利润,判断是否需要更新历史最大利润,之后还要判断是否要更新历史最低价格。

代码

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let min = prices[0], profit = 0;
    for(let i = 1; i < prices.length; i++) {
        profit = Math.max(profit, prices[i] - min);
        min = Math.min(min, prices[i]);
    }
    return profit;
};

扩展

在评论区,看到说这个类似最大子数组问题,百度了一番,其描述是给定一个数组,找出一个元素连续的子数组,并保证该子数组的元素和最大。

再回来看着问题,给定一个数组,找出元素之差最大的值。往最大子数组问题靠,就是给定一个数组,找出元素连续的子数组,并保证该子数组的最大元素和最小元素之的差值最大。有点那味了。。。

关于最大子数组问题,是用分治法解决的,先留个坑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值