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

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

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

import java.util.*;


public class Solution {
    /**
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        if(prices.length==1){
            return 0;
        }
        // write code here
        //表示第几天买入第几天卖出的最收益
        int dp[][]=new int[prices.length][prices.length];
	  //代表第1天买入第二天卖出的收益
        dp[0][1]=prices[1]-prices[0];
        for(int i=0;i<prices.length-1;i++){
            for(int j=i+1;j<prices.length;j++){
			  //第i天买入第j天卖出的收益为前一天最大收益与今天卖出最大收益的最大值
                dp[i][j]=Math.max(dp[i][j-1],prices[j]-prices[i]);
                
            }
        }
	  //找出最大值
        int max=0;
        for(int i=0;i<prices.length;i++){
            for(int j=0;j<prices.length;j++){
                if(dp[i][j]>max){
                    max=dp[i][j];
                }
            }
        }

        return max;
    }
}

全部评论

相关推荐

牛客36400893...:我不是这个专业的,但是简历确实没有吸引我的亮点,而且废话太多没耐心看
0offer是寒冬太冷还...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务