LeetCode WIith JS || 121. 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.
示例输入输出:
[7, 1, 5, 3, 6, 4]===>[5]//因为6-1=5
[7, 6, 4, 3, 1]===>[0]//因为一直在亏损,没有进行购入交易

大白话

给出一组代表股票每日价值的数组,用户可选择任意时刻购入抛出,现在要用户在最佳的时间购入抛出股票以获得最大的收益,求最大收益

原题目链接

121. Best Time to Buy and Sell Stock

思路

首先理清下题目的意思,就是求数组序列中的最大差值,只不过只能是后一个元素比前一个大的情况,不能是前一个比后一个大的情况下的差值

于是我的想法又出来了。what a 首当其冲的 algorithms
这里写图片描述

 var maxProfit = function(prices) {
    var max_profit = 0;
    var cur_profit = 0;
    for(var i = 0;i<prices.length;i++){
        for(var j = i+1;j<prices.length;j++){
            //两次循环,比较当前元素和它以后的所有的元素
            if(prices[j]>prices[i]){//如果比当前的大
                cur_profit = prices[j] - prices[i];
                //那么当前的利润就是它了!
            }
            if(cur_profit>max_profit){
                max_profit = cur_profit;
                //然后在当前利润的所有值中换最大利润
            }
        }
    }
    return max_profit;
};

AC代码

 var maxProfit = function(prices) {
    var max_profit = 0;
    var cur_profit = 0;
    for(var i = 0;i<prices.length;i++){
        for(var j = i+1;j<prices.length;j++){
            if(prices[j]>prices[i]){
                cur_profit = prices[j] - prices[i];
                //console.log(cur_profit);
            }
            if(cur_profit>max_profit){
                max_profit = cur_profit;
            }
        }
    }
    return max_profit;


};
    // 更高效的
    var min = Number.MAX_SAFE_INTEGER; //js整数里的最大值
    var max = 0;
    for (var i = 0; i < prices.length; i++) {
        min = Math.min(min, prices[i]);
        console.log(min);
        max = Math.max(max, prices[i] - min);
        console.log(max);
    }
    return max;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值