【LeetCode】Best Time to Buy and Sell Stock 解题报告

来源:互联网 发布:广数g90编程实例 编辑:程序博客网 时间:2024/05/17 19:18

Best Time to Buy and Sell Stock

[LeetCode]

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

Total Accepted: 98941 Total Submissions: 274449 Difficulty: Easy

Question

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.

Ways

动态规划求解。

因为买股票再卖掉是要求有先后顺序的。肯定是在前面找到最小值,再找到后面的最大值。不不不,应该说是找到当前项的值与之前最小值的差值的最大值。

动态规划问题,可以用数组去写。我偷看别人的,没用数组。

1.保存在见到这个数值时,之前的所有值的最小值。
2.记录当前值与这个最小值的差。
3.找到在所有里边差值的最大值。

不得不说下面这个方法还是很巧的。因为没有笨的像我一样在每个值时都去遍历查找之前所有值的最小值。而是采用保存下来的方法。

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length<2) return 0;        int maxProfit=0;        int min=prices[0];        int cur=0;        for(int i=1;i<prices.length;i++){            cur=prices[i];            min=Math.min(min,cur);            maxProfit=Math.max(maxProfit,cur-min);        }        return maxProfit;    }}

AC:3ms

Date

2016/5/1 17:59:24

0 0