码迷,mamicode.com
首页 > 编程语言 > 详细

【数组】Best Time to Buy and Sell Stock I/II

时间:2016-01-16 01:22:28      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

Best Time to Buy and Sell Stock 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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

思路:

只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o....i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    if(prices.length==0){
        return 0;
    }
    var n=prices.length,low=2147483647,ans=0;
    for(var i=0;i<n;i++){
        if(prices[i]<low){
            low=prices[i];
        }else if(prices[i]-low>ans){
            ans=prices[i]-low;
        }
    }
    
    return ans;
};

 

Best Time to Buy and Sell Stock I

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

思路:

此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var n=prices.length,res=0;
    
    if(n==0){
        return 0;
    }

    for(var i=1;i<n;i++){
        if(prices[i]>prices[i-1]){
            res+=prices[i]-prices[i-1]
        }
    }
    
    return res;
};

 

【数组】Best Time to Buy and Sell Stock I/II

标签:

原文地址:http://www.cnblogs.com/shytong/p/5134809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!