Best Time to Buy and Sell Stock(LeetCode)

来源:互联网 发布:手机淘宝店铺链接在哪? 编辑:程序博客网 时间:2024/05/23 21:39

题目:

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.


题目分析:

题目给出一个数组,每个数代表一天股票的价格。总共只能进行一笔交易(一买一卖)。问最多能挣多少钱?


思路:

暂略


注意点:

  1. 可以当天买进卖出,即收益为0。当其他时候收益为负,0有可能是最大收益。
  2. 注意,最后如果result < 0,则返回0即可



代码:

public class Solution {    public int maxProfit(int[] prices) {        if (prices.length == 0){//to judge an array is empty or not, cannot use "prices == null", but should use "prices.length == 0"            return 0;        }        int result = prices[prices.length - 1] - prices[0];        int begin = 0;                while (begin < prices.length){            int minIndex = begin, maxIndex = prices.length - 1;            for (int i = prices.length - 1; i > minIndex; i--){                if (prices[i] > prices[maxIndex]){                    maxIndex = i;                }            }            for (int i = begin; i < maxIndex; i++){                if (prices[i] < prices[minIndex]){                    minIndex = i;                }            }            int profit = prices[maxIndex] - prices[minIndex];            if (profit > result){                result = profit;            }            begin = maxIndex + 1;        }        if (result < 0){            return 0;        }        return result;    }}



0 0
原创粉丝点击