2020--07--17 单次买入卖出股票最大利润

best-time-to-buy-and-sell-stock

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

题目描述
假设你有一个数组,其中第i个元素是某只股票在第i天的价格。
如果你最多只能完成一笔交易(即买一股和卖一股股票),设计一个算法来求最大利润。

Say you have an array for which the i th 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.
示例1
输入
[1,4,2]
输出
3
这道题的思路是贪心算法
首先用一个greed方法,重新开一个数组来记录:当前第i天的最大利润,即第i天的值减去索引0到i-1的最小值
其次只需要返回新数组的最大值即可

代码实现:

//寻找数组0到index的最大值
    public int max(int[] A,int index){
        int max=A[0];
        for (int i = 1; i <= index; i++) {
            if (A[i]>max)max=A[i];
        }
        return max;
    }
//寻找数组0到index最小值
  public int min(int[] A,int index){
        int min=A[0];
        for (int i = 1; i <= index; i++) {
            if (A[i]<min)min=A[i];
        }
        return min;
    }
//贪心,用新数组profit记录当前最优
    public int greed(int[] A){
        int profit[] = new int[A.length];
        for (int i = 0; i < A.length; i++) {
            profit[i] = A[i]-min(A,i-1)>0? (A[i]-min(A,i-1)):0;
        }
        return max(profit,profit.length-1);//返回profit的最大值
    }
    public int maxProfit (int[] prices) {
        if (prices.length<=0)return 0;//空数组
        else
        return greed(prices);
    }
全部评论

相关推荐

10-22 20:17
已编辑
门头沟学院 Python
敢逐云霄志:后端没92学历+大厂实习基本别想在秋招约面了,笔试可能都不会给你发,我双非本3段实习,一大,中,一小,中大厂笔试做了一堆,大厂就只有字节给面,其他全没动静,根本轮不到双非。
你觉得第一学历对求职有影...
点赞 评论 收藏
分享
Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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