LeetCode 121 -Best Time to Buy and Sell Stock ( JAVA )

来源:互联网 发布:mac怎么分区移动硬盘pc 编辑:程序博客网 时间:2024/06/05 04:05

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.



public class Solution {    public int maxProfit(int[] prices) {        if(prices.length == 0 ){            return 0;        }        int profit = 0;        int min = prices[0];        for(int i=1;i<prices.length;i++){            if(min > prices[i]){                min = prices[i];            }else{                if(profit < prices[i] - min){                    profit = prices[i] - min;                }            }        }        return profit;    }}





总结:看到题目一般都会突然相处两个for循环,就完美结果了,但是超时了,时间复杂度太高了,本题目不通过,之后我对题目进行了,分析结果思路偏了一下,还是修炼的不到家,看了一眼discuss上面大神的回答,简直是太聪明的回答了,膜拜,解题思路是,遍历数组寻找最小的数字,之后在最当前的数值减去最小的数字进行比较,如果大,就复制给profit,最后返回一个profit。




尴尬,看了一下discuss里面的,有一个代码超级简洁,但是有一个问题就是会造成多次加多次减,比如{1,2,3} (2-1)+(3-2)



public class Solution {public int maxProfit(int[] prices) {    int total = 0;    for (int i=0; i< prices.length-1; i++) {        if (prices[i+1]>prices[i]) total += prices[i+1]-prices[i];    }    return total;}




0 0
原创粉丝点击