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

来源:互联网 发布:成都软件专修学院 编辑:程序博客网 时间:2024/06/07 00:59

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

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description

题目描述:

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).

Ways

这个题有点搞笑,根本不是贪心算法,这个题不是说可以任意的挑选,而是要按照每天的顺序挑选。这样就很简单了,只要后面的一天比这天的价格高就买入卖出就可。

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

Date

2017 年 4 月 20 日

0 0
原创粉丝点击