900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > LeetCode 121 Best Time to Buy and Sell Stock

LeetCode 121 Best Time to Buy and Sell Stock

时间:2019-11-12 01:17:56

相关推荐

LeetCode 121 Best Time to Buy and Sell Stock

Say you have an array for which theithelement 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.

用一个数组A[n-1]来存储当天与前一天股票的差价,从而将该题转化为最大子序列和的问题。仅仅只是没有负值。最小为0罢了。

A[i]表示第i+1天股票价格与第i天的股票价格的差值。

public class Solution {public int maxsum(int [] num){int sum=0;int max=Integer.MIN_VALUE;for(int i=0;i<num.length;i++){sum+=num[i];if(max<sum) max=sum;if(sum<0) sum=0;}return max>0?max:0;}public int maxProfit(int[] prices) {if(prices.length==0||prices.length==1) return 0;int [] sub=new int [prices.length-1];for(int i=0;i<sub.length;i++){sub[i]=prices[i+1]-prices[i];}return maxsum(sub);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。