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);
    }
全部评论

相关推荐

lingo12:1.最好加个业务项目,大部分面试官工作以后会更偏重业务 2.实习部分描述一般般,可能hr看到会觉得你产出不够不给你过简历 3.蓝桥杯这些大部分人都有的,不如不写,反而减分项。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务