Leetcode-122. Best Time to Buy and Sell Stock II

来源:互联网 发布:python 日期加减 月份 编辑:程序博客网 时间:2024/06/04 19:47

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

说实话,我一开始被这个题目吓住了,以为考虑不周全,后来发现,只要每次是递增我就卖就好了。。我觉得题目的本意应该是对于同一个element,你不能同时买卖。Your runtime beats 58.18% of java submissions.

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





0 0
原创粉丝点击