leetCode 系列:best time to buy and sell stock

来源:互联网 发布:网络骚扰电话怎么举报 编辑:程序博客网 时间:2024/05/19 03:43

由于最近在准备找工作,会刷写LeetCode的经典题目。因为最近编码能力实在不强,有些题目需要借鉴其他博主或者大神的解题思路,如有冒犯,请多原谅。如有错误,请指正,定会虚心接受并改正,不胜感激!

题目描述:

Say you have an array for which the i th element is the price of a given stock on dayi.

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

大体意思就是:有一只股票的某些天的某些价格波动,如例子所示:第一天价格7,第二天的价格是1,问哪一天买入,哪一天卖出获得的利润最大。从例子看,第二天买入,第五天卖出获利最大,即利润为6-1=5,第一天是7,第二天是1,但是不会第二天买第一天卖,所以只能用买入那天的后面几天做卖出操作才可以获利。

package Array;/** * Created by wuxiaosi on 2017/9/24. */public class MaxProfit {    public static void main(String[] args) {        int[] num = {5,1,2,3,6,14};        int p=0;        for(int i=0;i<num.length;i++){            for(int j=i;j<num.length;j++){                if(num[j]-num[i]>p){                    p=num[j]-num[i];                }            }        }        System.out.print(p);    }}



阅读全文
0 0
原创粉丝点击