Best Time to Buy and Sell Stock

本文介绍了一种算法,用于从给定的股票价格数组中找到能够实现最大利润的买入和卖出时机,仅允许进行一次买卖操作。通过动态规划的方法,在单次遍历中确定最佳交易策略。

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.

题意就是已经知道一支股票某些天的交易价格(看来有背景啊,连交易价格都知道了),然后限定只能交易一次,然后试着找出利益最大化的交易价格

最终题意变成了,从一个数组中找出两个元素的最大差值,动态规划,一个遍历就找到了,不过要注意的,后一个元素一定要大于前一个元素,否则就亏本了。

如:[3,2,6,5,0,3],最终的交易价格为buy=2,sell=6

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0){
            return 0;
        }
        int buy = prices[0];
        int sell = prices[0];
        int profit = sell - buy;//最坏的收益是0,不能是负值,否则亏本
        for(int i = 1; i < prices.length; i++){
            if(prices[i] > sell){
                sell = prices[i];
                profit = sell - buy > profit ? sell - buy: profit;
            }else if(prices[i] < buy){
                buy = prices[i];
                sell = prices[i];
            }
            
        }
        return profit;
    }
}
跟字符串相关的题比起来,这些很容易了,一看到字符串相关的那些题头就大啊!!!!

Runtime: 218 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值