题解 | #买卖股票的最好时机(一)#

买卖股票的最好时机(一)

http://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec

/**
  * 
  * @param prices int整型一维数组 
  * @return int整型
  */
// function maxProfit( prices ) {
//     // write code here
//     if(prices.length<2)return 0;
//     let dp=new Array(prices.length).fill(new Array(2).fill(0))
      //请注意这样创建的js二维数组 是会产生问题的  会一列跟着改变 最好还是两次for循环创建把
//     console.log(dp)
//     dp[0][0]=0
//     dp[0][1]=-prices[0]
//         console.log(dp)

//     for(let i=1;i<prices.length;i++){
//         dp[i][0]=Math.max(dp[i-1][0],prices[i]+dp[i-1][1])
//         dp[i][1]=Math.max(dp[i-1],[1],-prices[i])
//     }
//     console.log(dp)
//     return dp[prices.length-1][0]
// }
// module.exports = {
//     maxProfit : maxProfit
// };

//   *
//   * @param prices int整型一维数组
//   * @return int整型
//   */
function maxProfit( prices ) {
    // write code here
    let n = prices.length;
    if(n <=1)    return 0;
    let minValue = prices[0],maxP = 0;
    for(let i = 0;i < n;i++){
        minValue = Math.min(minValue,prices[i]);
        maxP = Math.max(maxP,prices[i] - minValue);
    }
    return maxP;
}
module.exports = {
    maxProfit : maxProfit
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务